"""Shared read-only PChome growth mapping backlog summarizer."""

from __future__ import annotations

import hashlib
import json
import re
from pathlib import Path
from typing import Any

import requests

from services.ai_exception_contract import (
    AI_EXCEPTION_MODE_KEY,
    AI_EXCEPTION_MODE_MACHINE_VERIFIABLE,
    AI_EXCEPTION_REQUIRED_COUNT_KEY,
    AI_EXCEPTION_REQUIRED_KEY,
    LEGACY_HUMAN_REVIEW_REQUIRED_COUNT_KEY,
    LEGACY_HUMAN_REVIEW_REQUIRED_KEY,
    LEGACY_HUMAN_REVIEW_REQUIRED_LEGACY_KEY,
    LEGACY_PRIMARY_FLOW_COUNT_KEY,
    LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
    LEGACY_REVIEW_MODE_KEY,
    LEGACY_REVIEW_REQUIRED_COUNT_KEY,
    LEGACY_REVIEW_REQUIRED_KEY,
    PRIMARY_HUMAN_GATE_COUNT_KEY,
)


from services.pchome_mapping_backlog.policies import (
    BACKLOG_POLICY,
    OPERATOR_PREVIEW_POLICY,
    DIRECT_MAPPING_AUTO_SEARCH_PACKAGE_POLICY,
    DIRECT_MAPPING_CANDIDATE_DECISION_PACKAGE_POLICY,
    DIRECT_MAPPING_CANDIDATE_DECISION_LANE_CLOSEOUT_POLICY,
    DIRECT_MAPPING_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY,
    DIRECT_MAPPING_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_DECISION_PACKAGE_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_INPUT_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_MATERIALIZATION_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREFLIGHT_VERIFIER_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_PREFLIGHT_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_EXECUTOR_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_RECEIPT_REPLAY_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIER_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_ARTIFACT_RETENTION_POLICY,
    DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_POLICY,
    AI_AUTOMATION_READINESS_POLICY,
    AI_AUTOMATION_SURFACE_SUMMARY_POLICY,
    EVIDENCE_ENRICHMENT_PREVIEW_POLICY,
    EVIDENCE_SOURCE_PREVIEW_POLICY,
    PRODUCT_PAGE_EVIDENCE_PARSER_POLICY,
    EVIDENCE_FETCH_GATE_POLICY,
    EVIDENCE_MERGE_PREVIEW_POLICY,
    AUTO_POLICY_RECEIPT_GATE_POLICY,
    AUTO_POLICY_PERSISTENCE_GATE_POLICY,
    AUTO_POLICY_SCHEMA_MIGRATION_PREVIEW_POLICY,
    AUTO_POLICY_MIGRATION_FILE_PREVIEW_POLICY,
    AUTO_POLICY_APPLY_READINESS_CLOSEOUT_POLICY,
    AUTO_POLICY_MIGRATION_FILE_GENERATION_REQUEST_POLICY,
    AUTO_POLICY_MIGRATION_APPLY_GATE_PREVIEW_POLICY,
    AUTO_POLICY_DB_APPLY_REQUEST_GATE_PREVIEW_POLICY,
    AUTO_POLICY_DB_APPLY_EXECUTION_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_PACKAGE_POLICY,
    AUTO_POLICY_DB_APPLY_VERIFIER_ARTIFACT_PREVIEW_POLICY,
    AUTO_POLICY_DB_APPLY_FINAL_HANDOFF_PACKAGE_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_SHELL_PREVIEW_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_REQUEST_INTAKE_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_LANE_GUARD_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_ISSUER_GATE_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RETENTION_BOUNDARY_NO_WRITE_ARCHIVE_PROOF_CLOSEOUT_POLICY,
    AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_ARCHIVE_RETENTION_SEALED_HANDOFF_PROOF_CLOSEOUT_POLICY,
    PCHOME_FETCH_ALLOWED_DOMAIN,
    PCHOME_FETCH_MAX_BATCH_SIZE,
    PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    PCHOME_FETCH_MAX_HTML_BYTES,
    EXTERNAL_BENCHMARK_REFERENCES,
)
from services.pchome_mapping_backlog.artifacts import (
    _canonical_retry_exception_artifact_bytes,
    _resolve_retry_exception_artifact_path,
)
from services.pchome_mapping_backlog.contracts import (
    _ai_exception_compatibility_fields,
    _evidence_requires_ai_exception,
    _legacy_review_compatibility_fields,
    _summary_exception_count,
)
from services.pchome_mapping_backlog.controlled_apply_executor import (
    _fetch_pchome_product_match_by_momo_icode,
    _retry_exception_controlled_apply_executor_id,
    _selector_to_pchome_match_params,
    _upsert_pchome_product_match,
    build_controlled_apply_executor_from_preflight,
)
from services.pchome_mapping_backlog.controlled_apply_receipt import (
    _find_retry_exception_artifact_file,
    _load_retry_exception_json_artifact,
    _retry_exception_controlled_apply_receipt_replay_id,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package,
)
from services.pchome_mapping_backlog.controlled_apply_verifier import (
    build_controlled_apply_drift_verifier_from_replay,
)
from services.pchome_mapping_backlog.evidence import (
    _action_code,
    _action_label,
    _fetch_product_page_html,
    _first_present,
    _is_allowed_pchome_product_url,
    _pchome_product_url,
    _to_float,
    parse_pchome_product_page_evidence_html,
    parse_unit_package_basis,
)
from services.pchome_mapping_backlog.enrichment import (
    _build_evidence_task,
    _build_fetch_gate_candidates,
    _field_enrichment_sources,
    _source_plan_for_field,
    build_pchome_evidence_enrichment_preview,
    build_pchome_evidence_source_preview,
)
from services.pchome_mapping_backlog.reporter import (
    _build_ai_automation_plan,
    _build_external_benchmark_alignment,
    _evidence_completeness,
    build_pchome_mapping_operator_preview,
    compact_mapping_item,
    summarize_pchome_mapping_backlog,
)


def _build_direct_mapping_search_terms(product_name: str, max_terms: int) -> list[str]:
    try:
        from services.momo_crawler import build_targeted_momo_search_terms

        return build_targeted_momo_search_terms(product_name, max_terms=max_terms)
    except Exception:
        fallback = re.sub(r"\s+", " ", product_name or "").strip()
        return [fallback] if fallback else []


def _build_direct_mapping_search_target(target: dict[str, Any], max_terms: int) -> dict[str, Any]:
    evidence = target.get("evidence_completeness") or {}
    unit_basis = evidence.get("unit_package_basis") or {}
    risk_signals = list(unit_basis.get("risk_signals") or [])
    search_terms = _build_direct_mapping_search_terms(target.get("product_name") or "", max_terms)
    return {
        "pchome_product_id": target.get("pchome_product_id") or "",
        "product_name": target.get("product_name") or "",
        "product_url": target.get("product_url") or evidence.get("product_url"),
        "pchome_price": target.get("pchome_price"),
        "sales_7d": target.get("sales_7d"),
        "priority_score": target.get("priority_score"),
        "search_terms": search_terms,
        "search_term_count": len(search_terms),
        "identity_anchors": {
            "stable_product_id": bool(target.get("pchome_product_id")),
            "product_name_present": bool(target.get("product_name")),
            "product_url_present": bool(target.get("product_url") or evidence.get("product_url")),
            "price_present": target.get("pchome_price") not in (None, ""),
            "unit_basis_present": bool(unit_basis),
            "unit_package_basis": unit_basis,
            "risk_signals": risk_signals,
            "variant_sensitive": "variant_selection" in risk_signals,
            "bundle_or_promo_sensitive": "bundle_or_promo" in risk_signals,
        },
        "candidate_acceptance_gates": [
            "target_pchome_product_id_matches",
            "target_match_score_meets_min_score",
            "target_hard_veto_is_false",
            "auto_compare_type_is_total_price_or_unit_price_for_auto_persistence",
            "manual_review_candidates_route_to_machine_verifiable_decision_package",
            "no_database_write_from_search_package",
        ],
        "can_execute_read_only_search": bool(search_terms),
        "writes_database": False,
        "persists_candidate": False,
    }


def _search_candidates_by_target(candidates: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
    grouped: dict[str, list[dict[str, Any]]] = {}
    for candidate in candidates:
        target_id = str(candidate.get("target_pchome_product_id") or "").strip()
        if not target_id:
            target_id = "unknown"
        grouped.setdefault(target_id, []).append(candidate)
    return grouped


def _is_truthy_flag(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    if value in (None, ""):
        return False
    if isinstance(value, (int, float)):
        return bool(value)
    return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}


def _build_candidate_decision_id(candidate: dict[str, Any]) -> str:
    decision_basis = {
        "target_pchome_product_id": candidate.get("target_pchome_product_id"),
        "momo_product_id": candidate.get("product_id"),
        "momo_name": candidate.get("name"),
        "target_match_score": candidate.get("target_match_score"),
        "auto_compare_type": candidate.get("auto_compare_type"),
    }
    digest = hashlib.sha256(
        json.dumps(decision_basis, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    return f"pchome-direct-mapping-candidate-{digest[:16]}"


def _candidate_ready_for_no_write_receipt(candidate: dict[str, Any], min_score: float) -> bool:
    confidence = _to_float(candidate.get("target_match_score"))
    auto_compare_type = str(candidate.get("auto_compare_type") or "").strip()
    return (
        bool(str(candidate.get("target_pchome_product_id") or "").strip())
        and bool(str(candidate.get("product_id") or "").strip())
        and confidence >= min_score
        and auto_compare_type in {"total_price", "unit_price"}
        and not _is_truthy_flag(candidate.get("target_hard_veto"))
    )


def _build_candidate_decision_envelope(candidate: dict[str, Any], min_score: float) -> dict[str, Any]:
    confidence = _to_float(candidate.get("target_match_score"))
    auto_compare_type = str(candidate.get("auto_compare_type") or "").strip()
    hard_veto = _is_truthy_flag(candidate.get("target_hard_veto"))
    target_id = str(candidate.get("target_pchome_product_id") or "").strip()
    momo_product_id = str(candidate.get("product_id") or "").strip()
    can_route_to_receipt = _candidate_ready_for_no_write_receipt(candidate, min_score)
    failure_reasons = []
    if not target_id:
        failure_reasons.append("missing_target_pchome_product_id")
    if not momo_product_id:
        failure_reasons.append("missing_momo_product_id")
    if confidence < min_score:
        failure_reasons.append("target_match_score_below_min_score")
    if auto_compare_type not in {"total_price", "unit_price"}:
        failure_reasons.append("auto_compare_type_not_receipt_ready")
    if hard_veto:
        failure_reasons.append("target_hard_veto_true")

    decision = (
        "route_to_no_write_auto_compare_receipt"
        if can_route_to_receipt
        else "route_to_machine_review_decision"
    )
    return {
        "decision_id": _build_candidate_decision_id(candidate),
        "decision_type": "direct_mapping_candidate_decision",
        "stage": "P2_machine_verifiable_candidate_decision",
        "subject": {
            "target_pchome_product_id": target_id,
            "pchome_product_name": candidate.get("target_pchome_name") or candidate.get("target_product_name"),
            "momo_product_id": momo_product_id,
            "momo_product_name": candidate.get("name"),
            "momo_price": candidate.get("price"),
        },
        "decision": decision,
        "confidence": confidence,
        "data_quality": "ready_for_no_write_receipt" if can_route_to_receipt else "needs_machine_review",
        "failure_reasons": failure_reasons,
        "evidence": [
            {"key": "target_match_score", "value": candidate.get("target_match_score")},
            {"key": "min_score", "value": min_score},
            {"key": "auto_compare_type", "value": auto_compare_type},
            {"key": "target_hard_veto", "value": hard_veto},
            {"key": "target_price_basis", "value": candidate.get("target_price_basis")},
            {"key": "target_gap_pct", "value": candidate.get("target_gap_pct") or candidate.get("gap_pct")},
            {"key": "target_search_term", "value": candidate.get("target_search_term") or candidate.get("search_term")},
        ],
        "recommended_action": (
            "build_no_write_auto_compare_receipt"
            if can_route_to_receipt
            else "build_machine_review_exception_receipt"
        ),
        "expected_impact": "reduce_direct_mapping_backlog_after_verified_persistence",
        "guardrails": {
            "machine_actionable": True,
            "can_auto_execute": False,
            "writes_database": False,
            "persists_candidate": False,
            "requires_no_write_receipt": True,
            "requires_verifier_before_persistence": True,
            "manual_review_mode": "exception_only",
        },
    }


def _next_machine_actions_for_candidate_exception(failure_reasons: list[str]) -> list[str]:
    actions: list[str] = []
    if "auto_compare_type_not_receipt_ready" in failure_reasons:
        actions.extend([
            "run_variant_bundle_discriminator",
            "build_named_candidate_evidence_delta",
        ])
    if "target_hard_veto_true" in failure_reasons:
        actions.extend([
            "keep_candidate_out_of_no_write_receipt",
            "expand_search_terms_with_unit_basis",
        ])
    if "target_match_score_below_min_score" in failure_reasons:
        actions.append("expand_search_terms_with_brand_spec_anchors")
    if "missing_momo_product_id" in failure_reasons or "missing_target_pchome_product_id" in failure_reasons:
        actions.append("drop_incomplete_candidate_and_retry_search")
    if not actions:
        actions.append("build_machine_review_exception_receipt")
    return list(dict.fromkeys(actions))


def _build_candidate_exception_receipt(decision: dict[str, Any]) -> dict[str, Any]:
    failure_reasons = list(decision.get("failure_reasons") or [])
    receipt_basis = {
        "decision_id": decision.get("decision_id"),
        "failure_reasons": failure_reasons,
        "subject": decision.get("subject") or {},
    }
    receipt_hash = hashlib.sha256(
        json.dumps(receipt_basis, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    return {
        "receipt_id": f"pchome-direct-mapping-exception-{receipt_hash[:16]}",
        "source_decision_id": decision.get("decision_id"),
        "stage": "P2_machine_verifiable_exception_receipt",
        "subject": decision.get("subject") or {},
        "failure_reasons": failure_reasons,
        "next_machine_actions": _next_machine_actions_for_candidate_exception(failure_reasons),
        "data_quality": decision.get("data_quality") or "needs_machine_review",
        "confidence": decision.get("confidence"),
        "expected_resolution": "machine_verifiable_auto_resolution",
        "guardrails": {
            "machine_actionable": True,
            "can_auto_execute": False,
            "writes_database": False,
            "persists_candidate": False,
            "requires_retry_or_evidence_delta": True,
            "requires_verifier_before_persistence": True,
            "manual_review_mode": "exception_only",
        },
    }


def _unit_basis_search_terms_from_subject(subject: dict[str, Any], max_terms: int = 8) -> list[str]:
    pchome_name = str(subject.get("pchome_product_name") or "").strip()
    momo_name = str(subject.get("momo_product_name") or "").strip()
    source_name = pchome_name or momo_name
    terms = _build_direct_mapping_search_terms(source_name, max_terms=3)
    basis = parse_unit_package_basis(source_name) if source_name else {}
    unit_measure = basis.get("unit_pricing_measure") or {}
    base_measure = basis.get("unit_pricing_base_measure") or {}
    quantity_terms: list[str] = []
    if unit_measure.get("value") and unit_measure.get("unit"):
        quantity_terms.append(f"{unit_measure.get('value'):g}{unit_measure.get('unit')}")
    if base_measure.get("value") and base_measure.get("unit"):
        quantity_terms.append(f"每{base_measure.get('value'):g}{base_measure.get('unit')}")
    if basis.get("estimated_total_quantity") and basis.get("unit_label"):
        quantity_terms.append(f"{basis.get('estimated_total_quantity'):g}{basis.get('unit_label')}")
    if basis.get("multipliers"):
        quantity_terms.append("x".join(str(item) for item in basis.get("multipliers") or []))

    for quantity_term in quantity_terms:
        if source_name:
            terms.append(f"{source_name} {quantity_term}")
    if source_name and ("bundle_or_promo" in (basis.get("risk_signals") or [])):
        terms.append(f"{source_name} 單入")
    if source_name and quantity_terms:
        terms.append(f"{source_name} 單位價")
    return list(dict.fromkeys(term for term in terms if term))[:max_terms]


def _build_variant_bundle_discriminator(subject: dict[str, Any], failure_reasons: list[str]) -> dict[str, Any]:
    pchome_name = str(subject.get("pchome_product_name") or "").strip()
    momo_name = str(subject.get("momo_product_name") or "").strip()
    target_basis = parse_unit_package_basis(pchome_name) if pchome_name else {}
    momo_basis = parse_unit_package_basis(momo_name) if momo_name else {}
    signals = set(target_basis.get("risk_signals") or [])
    signals.update(momo_basis.get("risk_signals") or [])
    if "auto_compare_type_not_receipt_ready" in failure_reasons:
        signals.add("needs_auto_compare_type_resolution")
    if "target_hard_veto_true" in failure_reasons:
        signals.add("target_identity_veto_blocks_receipt")

    return {
        "resolver": "variant_bundle_discriminator",
        "decision": "blocks_no_write_receipt_until_resolved" if signals else "identity_delta_only",
        "risk_signals": sorted(signals),
        "target_unit_package_basis": target_basis,
        "momo_unit_package_basis": momo_basis,
        "checks": [
            "same_brand_or_named_line",
            "same_quantity_or_convertible_unit_basis",
            "same_variant_or_color_scope",
            "same_bundle_or_single_item_scope",
        ],
        "writes_database": False,
    }


def _build_named_candidate_evidence_delta(subject: dict[str, Any], failure_reasons: list[str]) -> dict[str, Any]:
    evidence_keys = [
        "target_pchome_product_id",
        "pchome_product_name",
        "momo_product_id",
        "momo_product_name",
        "confidence",
        "failure_reasons",
    ]
    missing_keys = [
        key
        for key in ("target_pchome_product_id", "pchome_product_name", "momo_product_id", "momo_product_name")
        if not subject.get(key)
    ]
    return {
        "resolver": "named_candidate_evidence_delta",
        "named_evidence_keys": evidence_keys,
        "missing_evidence_keys": missing_keys,
        "failure_reasons": failure_reasons,
        "resolution": "ready_for_retry_search" if not missing_keys else "drop_incomplete_candidate_and_retry_search",
        "writes_database": False,
    }


def _build_candidate_exception_auto_resolution_artifact(receipt: dict[str, Any]) -> dict[str, Any]:
    subject = receipt.get("subject") or {}
    failure_reasons = list(receipt.get("failure_reasons") or [])
    next_actions = list(receipt.get("next_machine_actions") or [])
    artifact_basis = {
        "receipt_id": receipt.get("receipt_id"),
        "failure_reasons": failure_reasons,
        "next_actions": next_actions,
        "subject": subject,
    }
    artifact_hash = hashlib.sha256(
        json.dumps(artifact_basis, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    resolvers: dict[str, Any] = {}
    if "run_variant_bundle_discriminator" in next_actions:
        resolvers["variant_bundle_discriminator"] = _build_variant_bundle_discriminator(
            subject,
            failure_reasons,
        )
    if "build_named_candidate_evidence_delta" in next_actions:
        resolvers["named_candidate_evidence_delta"] = _build_named_candidate_evidence_delta(
            subject,
            failure_reasons,
        )
    if "expand_search_terms_with_unit_basis" in next_actions:
        resolvers["unit_basis_search_expansion"] = {
            "resolver": "unit_basis_search_expansion",
            "expanded_search_terms": _unit_basis_search_terms_from_subject(subject),
            "retry_package": "direct_mapping_auto_search_package",
            "writes_database": False,
        }
    if "expand_search_terms_with_brand_spec_anchors" in next_actions:
        resolvers["brand_spec_search_expansion"] = {
            "resolver": "brand_spec_search_expansion",
            "expanded_search_terms": _build_direct_mapping_search_terms(
                str(subject.get("pchome_product_name") or subject.get("momo_product_name") or ""),
                max_terms=6,
            ),
            "retry_package": "direct_mapping_auto_search_package",
            "writes_database": False,
        }

    resolver_count = len(resolvers)
    retry_search_ready = any(key.endswith("search_expansion") for key in resolvers)
    evidence_delta_ready = "named_candidate_evidence_delta" in resolvers

    return {
        "artifact_id": f"pchome-direct-mapping-exception-resolution-{artifact_hash[:16]}",
        "source_receipt_id": receipt.get("receipt_id"),
        "source_decision_id": receipt.get("source_decision_id"),
        "stage": "P2_machine_verifiable_exception_auto_resolution",
        "subject": subject,
        "failure_reasons": failure_reasons,
        "machine_actions": next_actions,
        "resolvers": resolvers,
        "resolution_status": "AUTO_RESOLUTION_ARTIFACT_READY",
        "execution_receipt": {
            "resolver_artifact_built": True,
            "resolver_count": resolver_count,
            "ready_for_retry_search": retry_search_ready,
            "ready_for_evidence_delta": evidence_delta_ready,
            "writes_database": False,
            "persists_candidate": False,
        },
        "next_package": "direct_mapping_candidate_decision_package_after_retry",
        "guardrails": {
            "machine_actionable": True,
            "can_auto_execute_read_only": True,
            "writes_database": False,
            "persists_candidate": False,
            "requires_verifier_before_persistence": True,
        },
    }


def _build_candidate_exception_auto_resolution_artifacts(
    exception_receipts: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    return [
        _build_candidate_exception_auto_resolution_artifact(receipt)
        for receipt in exception_receipts
    ]


def _summarize_exception_auto_resolution_artifacts(artifacts: list[dict[str, Any]]) -> dict[str, int]:
    resolver_counts = {
        "variant_bundle_discriminator_count": 0,
        "named_candidate_evidence_delta_count": 0,
        "unit_basis_search_expansion_count": 0,
        "brand_spec_search_expansion_count": 0,
    }
    retry_search_action_count = 0
    for artifact in artifacts:
        resolvers = artifact.get("resolvers") or {}
        for key in resolver_counts:
            resolver_name = key.removesuffix("_count")
            if resolver_name in resolvers:
                resolver_counts[key] += 1
        if any(key.endswith("search_expansion") for key in resolvers):
            retry_search_action_count += 1
    return {
        "exception_auto_resolution_artifact_count": len(artifacts),
        "retry_search_action_count": retry_search_action_count,
        **resolver_counts,
        "writes_database_count": 0,
    }


def _expanded_retry_search_terms_from_artifact(artifact: dict[str, Any]) -> list[str]:
    terms: list[str] = []
    resolvers = artifact.get("resolvers") or {}
    for key in ("unit_basis_search_expansion", "brand_spec_search_expansion"):
        resolver = resolvers.get(key) or {}
        terms.extend(str(term).strip() for term in resolver.get("expanded_search_terms") or [])
    return list(dict.fromkeys(term for term in terms if term))


def _retry_search_targets_from_artifact(
    artifact: dict[str, Any],
    *,
    max_terms_per_product: int,
) -> list[dict[str, Any]]:
    subject = artifact.get("subject") or {}
    terms = _expanded_retry_search_terms_from_artifact(artifact)[:max_terms_per_product]
    return [
        {
            "product_id": subject.get("target_pchome_product_id") or "",
            "name": term,
            "price": subject.get("pchome_price"),
            "source_artifact_id": artifact.get("artifact_id"),
            "source_resolution_receipt_id": artifact.get("source_receipt_id"),
        }
        for term in terms
        if term
    ]


def _run_retry_search_for_artifact(
    artifact: dict[str, Any],
    *,
    execute_retry_search: bool,
    limit_per_product: int,
    max_terms_per_product: int,
    min_score: float,
    search_func: Any = None,
) -> dict[str, Any]:
    targets = _retry_search_targets_from_artifact(
        artifact,
        max_terms_per_product=max_terms_per_product,
    )
    if not execute_retry_search or not targets:
        return {
            "executed": False,
            "search_success": None,
            "search_message": "retry_search_not_executed" if targets else "no_retry_search_terms",
            "targets": targets,
            "candidate_count": 0,
            "candidates": [],
        }

    if search_func is None:
        from services.momo_crawler import search_momo_products_for_pchome_products

        search_func = search_momo_products_for_pchome_products
    search_success, search_message, candidates = search_func(
        targets,
        limit_per_product=limit_per_product,
        max_products=len(targets),
        max_terms_per_product=1,
        min_score=min_score,
    )
    candidates = list(candidates or [])
    for candidate in candidates:
        candidate["source_resolution_artifact_id"] = artifact.get("artifact_id")
        candidate["source_resolution_receipt_id"] = artifact.get("source_receipt_id")
        candidate["retry_search_source"] = "candidate_exception_resolution_closeout"

    return {
        "executed": True,
        "search_success": bool(search_success),
        "search_message": search_message,
        "targets": targets,
        "candidate_count": len(candidates),
        "candidates": candidates[:20],
    }


def _build_candidate_exception_resolution_closeout_receipt(
    artifact: dict[str, Any],
    retry_search_result: dict[str, Any],
) -> dict[str, Any]:
    resolvers = artifact.get("resolvers") or {}
    evidence_delta = resolvers.get("named_candidate_evidence_delta") or {}
    retry_search_ready = bool(_expanded_retry_search_terms_from_artifact(artifact))
    closeout_basis = {
        "artifact_id": artifact.get("artifact_id"),
        "resolver_keys": sorted(resolvers.keys()),
        "retry_search_ready": retry_search_ready,
        "retry_candidate_count": retry_search_result.get("candidate_count"),
    }
    closeout_hash = hashlib.sha256(
        json.dumps(closeout_basis, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    retry_candidate_count = int(retry_search_result.get("candidate_count") or 0)
    return {
        "receipt_id": f"pchome-direct-mapping-exception-closeout-{closeout_hash[:16]}",
        "source_artifact_id": artifact.get("artifact_id"),
        "source_receipt_id": artifact.get("source_receipt_id"),
        "source_decision_id": artifact.get("source_decision_id"),
        "stage": "P2_machine_verifiable_exception_resolution_closeout",
        "subject": artifact.get("subject") or {},
        "resolution_status": "AUTO_RESOLUTION_CLOSEOUT_READY",
        "completed_resolvers": sorted(resolvers.keys()),
        "evidence_delta": {
            "ready": bool(evidence_delta),
            "missing_evidence_keys": list(evidence_delta.get("missing_evidence_keys") or []),
            "resolution": evidence_delta.get("resolution") or "not_applicable",
        },
        "retry_search": {
            "ready": retry_search_ready,
            "executed": bool(retry_search_result.get("executed")),
            "search_success": retry_search_result.get("search_success"),
            "search_message": retry_search_result.get("search_message"),
            "target_count": len(retry_search_result.get("targets") or []),
            "candidate_count": retry_candidate_count,
            "targets": retry_search_result.get("targets") or [],
            "candidates": retry_search_result.get("candidates") or [],
        },
        "next_package": (
            "direct_mapping_candidate_decision_package_after_retry"
            if retry_search_ready
            else "no_write_receipt_verifier_when_identity_delta_clears"
        ),
        "guardrails": {
            "machine_actionable": True,
            "can_auto_execute_read_only": retry_search_ready,
            "writes_database": False,
            "persists_candidate": False,
            "requires_no_write_receipt": True,
            "requires_verifier_before_persistence": True,
        },
    }


def _build_candidate_exception_resolution_closeout_receipts(
    artifacts: list[dict[str, Any]],
    *,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> list[dict[str, Any]]:
    receipts = []
    for artifact in artifacts:
        retry_search_result = _run_retry_search_for_artifact(
            artifact,
            execute_retry_search=execute_retry_search,
            limit_per_product=limit_per_product,
            max_terms_per_product=max_terms_per_product,
            min_score=min_score,
            search_func=search_func,
        )
        receipts.append(_build_candidate_exception_resolution_closeout_receipt(artifact, retry_search_result))
    return receipts


def _summarize_exception_resolution_closeout_receipts(receipts: list[dict[str, Any]]) -> dict[str, int]:
    retry_search_ready_count = 0
    retry_search_executed_count = 0
    retry_candidate_count = 0
    evidence_delta_closeout_count = 0
    ready_for_next_decision_count = 0
    for receipt in receipts:
        retry_search = receipt.get("retry_search") or {}
        evidence_delta = receipt.get("evidence_delta") or {}
        retry_ready = bool(retry_search.get("ready"))
        retry_executed = bool(retry_search.get("executed"))
        retry_candidates = int(retry_search.get("candidate_count") or 0)
        if retry_ready:
            retry_search_ready_count += 1
        if retry_executed:
            retry_search_executed_count += 1
        if evidence_delta.get("ready"):
            evidence_delta_closeout_count += 1
        retry_candidate_count += retry_candidates
        if retry_candidates:
            ready_for_next_decision_count += 1

    return {
        "exception_resolution_closeout_receipt_count": len(receipts),
        "retry_search_ready_count": retry_search_ready_count,
        "retry_search_executed_count": retry_search_executed_count,
        "retry_candidate_count": retry_candidate_count,
        "evidence_delta_closeout_count": evidence_delta_closeout_count,
        "ready_for_next_candidate_decision_count": ready_for_next_decision_count,
        "writes_database_count": 0,
    }


def _retry_candidates_from_closeout_receipts(receipts: list[dict[str, Any]]) -> list[dict[str, Any]]:
    retry_candidates: list[dict[str, Any]] = []
    seen: set[str] = set()
    for receipt in receipts:
        retry_search = receipt.get("retry_search") or {}
        for candidate in retry_search.get("candidates") or []:
            candidate = dict(candidate)
            candidate.setdefault("source_resolution_closeout_receipt_id", receipt.get("receipt_id"))
            candidate.setdefault("source_resolution_artifact_id", receipt.get("source_artifact_id"))
            dedupe_key = "|".join([
                str(candidate.get("target_pchome_product_id") or ""),
                str(candidate.get("product_id") or ""),
                str(candidate.get("source_resolution_artifact_id") or ""),
            ])
            if dedupe_key in seen:
                continue
            seen.add(dedupe_key)
            retry_candidates.append(candidate)
    return retry_candidates


def _build_exception_closeout_no_write_verifier_receipt(closeout_receipt: dict[str, Any]) -> dict[str, Any]:
    subject = closeout_receipt.get("subject") or {}
    evidence_delta = closeout_receipt.get("evidence_delta") or {}
    retry_search = closeout_receipt.get("retry_search") or {}
    retry_search_ready = bool(retry_search.get("ready"))
    retry_search_executed = bool(retry_search.get("executed"))
    retry_candidate_count = int(retry_search.get("candidate_count") or 0)
    missing_evidence_keys = list(evidence_delta.get("missing_evidence_keys") or [])
    checks = [
        {
            "check": "source_closeout_ready",
            "passed": closeout_receipt.get("resolution_status") == "AUTO_RESOLUTION_CLOSEOUT_READY",
        },
        {
            "check": "evidence_delta_ready",
            "passed": bool(evidence_delta.get("ready")),
        },
        {
            "check": "missing_evidence_keys_clear",
            "passed": not missing_evidence_keys,
        },
        {
            "check": "target_pchome_product_id_present",
            "passed": bool(subject.get("target_pchome_product_id")),
        },
        {
            "check": "momo_product_id_present",
            "passed": bool(subject.get("momo_product_id")),
        },
        {
            "check": "retry_search_queue_clear",
            "passed": (not retry_search_ready) or (retry_search_executed and retry_candidate_count == 0),
        },
        {
            "check": "database_write_locked",
            "passed": True,
        },
    ]
    ready = all(check["passed"] for check in checks)
    receipt_basis = {
        "source_closeout_receipt_id": closeout_receipt.get("receipt_id"),
        "source_artifact_id": closeout_receipt.get("source_artifact_id"),
        "subject": subject,
        "checks": checks,
    }
    receipt_hash = hashlib.sha256(
        json.dumps(receipt_basis, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    return {
        "receipt_id": f"pchome-direct-mapping-exception-closeout-verifier-{receipt_hash[:16]}",
        "source_closeout_receipt_id": closeout_receipt.get("receipt_id"),
        "source_artifact_id": closeout_receipt.get("source_artifact_id"),
        "source_decision_id": closeout_receipt.get("source_decision_id"),
        "stage": "P2_retry_exception_closeout_no_write_verifier_input",
        "receipt_status": "NO_WRITE_VERIFIER_INPUT_READY" if ready else "NO_WRITE_VERIFIER_INPUT_BLOCKED",
        "subject": subject,
        "evidence_delta": evidence_delta,
        "retry_search": {
            "ready": retry_search_ready,
            "executed": retry_search_executed,
            "candidate_count": retry_candidate_count,
        },
        "verification_checks": checks,
        "ready_for_no_write_verifier": ready,
        "ready_for_controlled_apply": False,
        "next_package": "auto_policy_db_apply_verifier_artifact_preview_after_exception_closeout",
        "guardrails": {
            "machine_actionable": True,
            "writes_database": False,
            "persists_candidate": False,
            "requires_no_write_receipt": True,
            "requires_verifier_before_persistence": True,
            "requires_rollback_and_readback": True,
        },
    }


def _build_exception_closeout_no_write_verifier_receipts(
    closeout_receipts: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    return [
        _build_exception_closeout_no_write_verifier_receipt(receipt)
        for receipt in closeout_receipts
    ]


def _summarize_exception_closeout_no_write_verifier_receipts(receipts: list[dict[str, Any]]) -> dict[str, int]:
    ready_count = sum(1 for receipt in receipts if receipt.get("ready_for_no_write_verifier"))
    retry_candidate_pending_count = sum(
        int((receipt.get("retry_search") or {}).get("candidate_count") or 0)
        for receipt in receipts
    )
    evidence_delta_ready_count = sum(
        1
        for receipt in receipts
        if (receipt.get("evidence_delta") or {}).get("ready")
    )
    return {
        "closeout_no_write_verifier_input_count": len(receipts),
        "ready_closeout_no_write_verifier_input_count": ready_count,
        "blocked_closeout_no_write_verifier_input_count": len(receipts) - ready_count,
        "evidence_delta_ready_for_verifier_count": evidence_delta_ready_count,
        "retry_candidate_pending_count": retry_candidate_pending_count,
        "writes_database_count": 0,
    }


def _build_no_write_auto_compare_verifier_receipt(decision: dict[str, Any]) -> dict[str, Any]:
    subject = decision.get("subject") or {}
    receipt_basis = {
        "decision_id": decision.get("decision_id"),
        "subject": subject,
        "confidence": decision.get("confidence"),
        "decision": decision.get("decision"),
    }
    receipt_hash = hashlib.sha256(
        json.dumps(receipt_basis, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    checks = [
        {
            "check": "routes_to_no_write_auto_compare_receipt",
            "passed": decision.get("decision") == "route_to_no_write_auto_compare_receipt",
        },
        {
            "check": "target_pchome_product_id_present",
            "passed": bool(subject.get("target_pchome_product_id")),
        },
        {
            "check": "momo_product_id_present",
            "passed": bool(subject.get("momo_product_id")),
        },
        {
            "check": "target_match_score_present",
            "passed": decision.get("confidence") not in (None, ""),
        },
        {
            "check": "database_write_locked",
            "passed": True,
        },
    ]
    ready = all(check["passed"] for check in checks)
    return {
        "receipt_id": f"pchome-direct-mapping-no-write-verifier-{receipt_hash[:16]}",
        "source_decision_id": decision.get("decision_id"),
        "stage": "P2_retry_candidate_no_write_verifier_input",
        "receipt_status": "NO_WRITE_VERIFIER_INPUT_READY" if ready else "NO_WRITE_VERIFIER_INPUT_BLOCKED",
        "subject": subject,
        "confidence": decision.get("confidence"),
        "verification_checks": checks,
        "ready_for_no_write_verifier": ready,
        "ready_for_controlled_apply": False,
        "next_package": "auto_policy_db_apply_verifier_artifact_preview_after_no_write_receipt",
        "guardrails": {
            "machine_actionable": True,
            "writes_database": False,
            "persists_candidate": False,
            "requires_no_write_receipt": True,
            "requires_verifier_before_persistence": True,
            "requires_rollback_and_readback": True,
        },
    }


def build_pchome_direct_mapping_auto_search_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Build a P1 no-write package for direct PChome-to-MOMO candidate search."""
    operator_preview = build_pchome_mapping_operator_preview(payload, batch_size=batch_size)
    operator_batch = operator_preview.get("operator_batch") or {}
    direct_targets = list(operator_batch.get("direct_mapping_targets") or [])
    batch_size = int(operator_batch.get("batch_size") or batch_size or 5)
    max_terms_per_product = max(1, min(int(max_terms_per_product or 5), 8))
    limit_per_product = max(1, min(int(limit_per_product or 8), 12))
    try:
        min_score = max(0.35, min(float(min_score), 0.95))
    except (TypeError, ValueError):
        min_score = 0.45

    search_targets = [
        _build_direct_mapping_search_target(target, max_terms=max_terms_per_product)
        for target in direct_targets
    ]
    read_only_targets = [
        {
            "product_id": target.get("pchome_product_id"),
            "name": target.get("product_name"),
            "price": target.get("pchome_price"),
            "sales_7d": target.get("sales_7d"),
            "priority_score": target.get("priority_score"),
        }
        for target in direct_targets
    ]

    search_success = None
    search_message = "search_not_executed"
    candidates: list[dict[str, Any]] = []
    if execute_search and read_only_targets:
        if search_func is None:
            from services.momo_crawler import search_momo_products_for_pchome_products

            search_func = search_momo_products_for_pchome_products
        search_success, search_message, candidates = search_func(
            read_only_targets,
            limit_per_product=limit_per_product,
            max_products=batch_size,
            max_terms_per_product=max_terms_per_product,
            min_score=min_score,
        )
        candidates = list(candidates or [])

    auto_candidates = [
        candidate
        for candidate in candidates
        if _candidate_ready_for_no_write_receipt(candidate, min_score)
    ]
    review_candidates = [
        candidate
        for candidate in candidates
        if not _candidate_ready_for_no_write_receipt(candidate, min_score)
    ]
    grouped_candidates = _search_candidates_by_target(candidates)
    for target in search_targets:
        target["candidate_count"] = len(grouped_candidates.get(target.get("pchome_product_id") or "", []))
        target["candidate_ids"] = [
            str(candidate.get("product_id") or "")
            for candidate in grouped_candidates.get(target.get("pchome_product_id") or "", [])[:5]
        ]

    if not direct_targets:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif execute_search and candidates:
        result = "DIRECT_MAPPING_CANDIDATES_FOUND"
    elif execute_search:
        result = "DIRECT_MAPPING_SEARCH_NO_CANDIDATES"
    else:
        result = "DIRECT_MAPPING_SEARCH_PACKAGE_READY"

    return {
        "policy": DIRECT_MAPPING_AUTO_SEARCH_PACKAGE_POLICY,
        "result": result,
        "success": bool(operator_preview.get("success")),
        "generated_at": operator_preview.get("generated_at"),
        "source_policy": operator_preview.get("policy"),
        "stats": operator_preview.get("stats") or {},
        "backlog": operator_preview.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((operator_preview.get("backlog") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": len(search_targets),
            "search_ready_target_count": sum(1 for target in search_targets if target.get("can_execute_read_only_search")),
            "planned_search_term_count": sum(int(target.get("search_term_count") or 0) for target in search_targets),
            "execute_search_count": 1 if execute_search else 0,
            "candidates_found_count": len(candidates),
            "auto_compare_candidate_count": len(auto_candidates),
            "review_candidate_count": len(review_candidates),
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "search_package": {
            "stage": "P1_direct_mapping_auto_search",
            "batch_size": batch_size,
            "execute_search": bool(execute_search),
            "limit_per_product": limit_per_product,
            "max_terms_per_product": max_terms_per_product,
            "min_score": min_score,
            "targets": search_targets,
        },
        "search_execution": {
            "executed": bool(execute_search),
            "search_success": search_success,
            "search_message": search_message,
            "candidate_count": len(candidates),
            "auto_compare_candidate_count": len(auto_candidates),
            "review_candidate_count": len(review_candidates),
            "writes_database": False,
            "syncs_external_offers": False,
        },
        "candidate_acceptance_policy": {
            "min_score": min_score,
            "auto_compare_types": ["total_price", "unit_price"],
            "requires_target_pchome_product_id": True,
            "rejects_hard_veto": True,
            "routes_manual_review_to_machine_verifiable_decision": True,
            "writes_database": False,
        },
        "candidate_preview": candidates[:20],
        "next_actions": [
            "Execute controlled read-only MOMO search for the selected direct mapping targets.",
            "Route auto-compare candidates into no-write receipt and verifier packages before persistence.",
            "Route manual-review candidates into machine-verifiable candidate decision packages, not free-form human review.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_candidate_decision_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Build a P2 no-write machine-verifiable decision package for direct mapping candidates."""
    search_package = build_pchome_direct_mapping_auto_search_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    candidates = list(search_package.get("candidate_preview") or [])
    effective_min_score = _to_float((search_package.get("candidate_acceptance_policy") or {}).get("min_score"))
    decision_envelopes = [
        _build_candidate_decision_envelope(candidate, min_score=effective_min_score)
        for candidate in candidates
    ]
    auto_compare_decisions = [
        envelope
        for envelope in decision_envelopes
        if envelope.get("decision") == "route_to_no_write_auto_compare_receipt"
    ]
    machine_review_decisions = [
        envelope
        for envelope in decision_envelopes
        if envelope.get("decision") == "route_to_machine_review_decision"
    ]
    machine_review_exception_receipts = [
        _build_candidate_exception_receipt(envelope)
        for envelope in machine_review_decisions
    ]
    exception_auto_resolution_artifacts = _build_candidate_exception_auto_resolution_artifacts(
        machine_review_exception_receipts
    )
    exception_auto_resolution_summary = _summarize_exception_auto_resolution_artifacts(
        exception_auto_resolution_artifacts
    )

    if not int((search_package.get("summary") or {}).get("selected_direct_mapping_count") or 0):
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif decision_envelopes:
        result = "DIRECT_MAPPING_CANDIDATE_DECISION_PACKAGE_READY"
    else:
        result = "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"

    return {
        "policy": DIRECT_MAPPING_CANDIDATE_DECISION_PACKAGE_POLICY,
        "result": result,
        "success": bool(search_package.get("success")),
        "generated_at": search_package.get("generated_at"),
        "source_policy": search_package.get("policy"),
        "stats": search_package.get("stats") or {},
        "backlog": search_package.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((search_package.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": int(
                (search_package.get("summary") or {}).get("selected_direct_mapping_count") or 0
            ),
            "candidates_found_count": len(candidates),
            "candidate_decision_count": len(decision_envelopes),
            "auto_compare_decision_count": len(auto_compare_decisions),
            "machine_review_decision_count": len(machine_review_decisions),
            "machine_review_exception_receipt_count": len(machine_review_exception_receipts),
            **exception_auto_resolution_summary,
            "can_auto_persist_now_count": 0,
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "decision_package": {
            "stage": "P2_machine_verifiable_candidate_decision",
            "execute_search": bool(execute_search),
            "candidate_decisions": decision_envelopes,
            "machine_review_exception_receipts": machine_review_exception_receipts,
            "machine_review_exception_auto_resolution_artifacts": exception_auto_resolution_artifacts,
            "manual_review_mode": "exception_only",
        },
        "decision_acceptance_policy": {
            "min_score": effective_min_score,
            "auto_compare_types": ["total_price", "unit_price"],
            "rejects_hard_veto": True,
            "requires_target_pchome_product_id": True,
            "requires_momo_product_id": True,
            "routes_non_ready_candidates_to_machine_review_decision": True,
            "writes_database": False,
        },
        "candidate_source_preview": candidates,
        "upstream_search_summary": search_package.get("summary") or {},
        "next_actions": [
            "Run controlled read-only search first when candidate_decision_count is zero.",
            "Send auto-compare decisions to no-write receipt generation before any persistence.",
            "Route machine-review decisions through exception receipts and auto-resolution artifacts.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_candidate_decision_lane_closeout_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
    artifact_root: str | Path | None = None,
    materialize_artifacts: bool = False,
) -> dict[str, Any]:
    """Close out the candidate-decision lane with receipt, replay, drift, and readiness proof."""
    decision_package = build_pchome_direct_mapping_candidate_decision_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = decision_package.get("decision_package") or {}
    decisions = list(package.get("candidate_decisions") or [])
    exception_receipts = list(package.get("machine_review_exception_receipts") or [])
    auto_resolution_artifacts = list(
        package.get("machine_review_exception_auto_resolution_artifacts") or []
    )
    summary = decision_package.get("summary") or {}
    selected_direct_count = int(summary.get("selected_direct_mapping_count") or 0)
    auto_compare_decisions = [
        item
        for item in decisions
        if item.get("decision") == "route_to_no_write_auto_compare_receipt"
    ]
    machine_review_decisions = [
        item
        for item in decisions
        if item.get("decision") == "route_to_machine_review_decision"
    ]
    receipt_entries = [
        {
            "decision_id": item.get("decision_id"),
            "decision": item.get("decision"),
            "subject": item.get("subject") or {},
            "confidence": item.get("confidence"),
            "failure_reasons": list(item.get("failure_reasons") or []),
            "ready_for_no_write_receipt": item.get("decision") == "route_to_no_write_auto_compare_receipt",
            "requires_auto_resolution": item.get("decision") == "route_to_machine_review_decision",
            "writes_database": False,
        }
        for item in decisions
    ]
    source_fingerprint_payload = {
        "policy": decision_package.get("policy"),
        "result": decision_package.get("result"),
        "summary": {
            "selected_direct_mapping_count": selected_direct_count,
            "candidate_decision_count": len(decisions),
            "auto_compare_decision_count": len(auto_compare_decisions),
            "machine_review_decision_count": len(machine_review_decisions),
            "machine_review_exception_receipt_count": len(exception_receipts),
            "exception_auto_resolution_artifact_count": len(auto_resolution_artifacts),
        },
        "decision_ids": [item.get("decision_id") for item in decisions],
        "exception_receipt_ids": [item.get("receipt_id") for item in exception_receipts],
    }
    source_fingerprint = hashlib.sha256(
        json.dumps(source_fingerprint_payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    receipt_id = f"pchome-direct-mapping-candidate-decision-lane-{source_fingerprint[:16]}"

    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
        product_status = "waiting_for_growth_input"
        next_machine_action = "wait_for_direct_mapping_backlog"
    elif decisions:
        result = "DIRECT_MAPPING_CANDIDATE_DECISION_LANE_CLOSEOUT_READY"
        product_status = "ready_for_next_automation"
        next_machine_action = "route_auto_compare_to_no_write_receipts_and_exceptions_to_auto_resolution"
    else:
        result = "WAITING_FOR_DIRECT_MAPPING_CANDIDATE_DECISION_LANE_CANDIDATES"
        product_status = "waiting_for_read_only_search"
        next_machine_action = "run_controlled_read_only_candidate_search"

    safety = {
        "ai_controlled": True,
        "read_only_preview": True,
        "receipt_replay": True,
        "drift_verifier": True,
        "product_readiness": True,
        "executes_search": bool(execute_search),
        "writes_database": False,
        "writes_database_count": 0,
        "persists_candidate": False,
        "syncs_external_offers": False,
        "dispatches_telegram": False,
        "llm_calls_in_preview": False,
        "gemini_allowed": False,
        "requires_production_version_truth": True,
    }
    closeout_summary = {
        "selected_direct_mapping_count": selected_direct_count,
        "candidate_decision_count": len(decisions),
        "auto_compare_decision_count": len(auto_compare_decisions),
        "machine_review_decision_count": len(machine_review_decisions),
        "machine_review_exception_receipt_count": len(exception_receipts),
        "exception_auto_resolution_artifact_count": len(auto_resolution_artifacts),
        "receipt_entry_count": len(receipt_entries),
        "receipt_payload_hash_ready_count": 1,
        "receipt_materialized_count": 0,
        "receipt_hash_match_count": 0,
        "replay_verified_count": 0,
        "drift_count": 0,
        "product_ready_count": 1 if product_status == "ready_for_next_automation" else 0,
        "primary_human_gate_count": 0,
        "writes_database_count": 0,
    }
    receipt_fingerprint_payload = {
        "policy": decision_package.get("policy"),
        "result": decision_package.get("result"),
        "summary": source_fingerprint_payload["summary"],
        "decision_ids": [item.get("decision_id") for item in decisions],
        "exception_receipt_ids": [item.get("receipt_id") for item in exception_receipts],
    }
    receipt_fingerprint = hashlib.sha256(
        json.dumps(receipt_fingerprint_payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    replay_verified = source_fingerprint == receipt_fingerprint
    drift_count = 0 if replay_verified else 1
    closeout_summary["replay_verified_count"] = 1 if replay_verified else 0
    closeout_summary["drift_count"] = drift_count
    receipt_payload = {
        "artifact_key": "direct_mapping_candidate_decision_lane_closeout_receipt",
        "receipt_id": receipt_id,
        "source_policy": DIRECT_MAPPING_CANDIDATE_DECISION_LANE_CLOSEOUT_POLICY,
        "source_decision_policy": decision_package.get("policy"),
        "source_decision_result": decision_package.get("result"),
        "result": result,
        "product_status": product_status,
        "next_machine_action": next_machine_action,
        "summary": dict(closeout_summary),
        "source_fingerprint": source_fingerprint,
        "receipt_fingerprint": receipt_fingerprint,
        "receipt_entries": receipt_entries,
        "exception_receipts": exception_receipts,
        "auto_resolution_artifacts": auto_resolution_artifacts,
        "safety": dict(safety),
    }
    receipt_bytes = _canonical_retry_exception_artifact_bytes(receipt_payload)
    receipt_sha = hashlib.sha256(receipt_bytes).hexdigest()
    receipt_relative_path = (
        "artifacts/pchome_growth/candidate_decision_lane_closeout/"
        f"{receipt_id}.json"
    )
    receipt_artifact = {
        "key": "direct_mapping_candidate_decision_lane_closeout_receipt",
        "artifact_type": "candidate_decision_lane_closeout_receipt",
        "relative_path": receipt_relative_path,
        "payload_sha256": receipt_sha,
        "byte_count": len(receipt_bytes),
        "payload": receipt_payload,
        "materialized": False,
        "writes_database": False,
    }
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    materialized_artifacts: list[dict[str, Any]] = []
    if materialize_artifacts and selected_direct_count:
        target_path = root / receipt_relative_path
        target_path.parent.mkdir(parents=True, exist_ok=True)
        target_path.write_bytes(receipt_bytes)
        materialized_artifacts.append({
            "key": receipt_artifact["key"],
            "relative_path": receipt_relative_path,
            "absolute_path": str(target_path),
            "payload_sha256": receipt_sha,
            "written_byte_count": target_path.stat().st_size,
            "writes_database": False,
        })
        receipt_artifact["materialized"] = True
        receipt_artifact["absolute_path"] = str(target_path)
    receipt_path = root / receipt_relative_path
    actual_sha = hashlib.sha256(receipt_path.read_bytes()).hexdigest() if receipt_path.exists() else ""
    receipt_hash_match = bool(actual_sha) and actual_sha == receipt_sha
    closeout_summary["receipt_materialized_count"] = len(materialized_artifacts) or (1 if receipt_hash_match else 0)
    closeout_summary["receipt_hash_match_count"] = 1 if receipt_hash_match else 0
    safety["writes_artifact_count"] = len(materialized_artifacts)

    checks = [
        {"check": "source_decision_package_loaded", "passed": bool(decision_package)},
        {
            "check": "candidate_decisions_match_summary",
            "passed": len(decisions) == int(summary.get("candidate_decision_count") or 0),
        },
        {"check": "receipt_payload_hash_is_sha256", "passed": len(receipt_sha) == 64},
        {"check": "receipt_replay_matches_source_fingerprint", "passed": replay_verified},
        {"check": "drift_count_zero", "passed": drift_count == 0},
        {
            "check": "receipt_materialized_when_requested",
            "passed": (not materialize_artifacts) or (selected_direct_count > 0 and receipt_path.exists()),
        },
        {
            "check": "receipt_hash_matches_expected_when_materialized",
            "passed": (not materialize_artifacts) or receipt_hash_match,
        },
        {"check": "candidate_decision_lane_closeout_does_not_write_database", "passed": True},
    ]

    return {
        "policy": DIRECT_MAPPING_CANDIDATE_DECISION_LANE_CLOSEOUT_POLICY,
        "result": result,
        "success": bool(decision_package.get("success")),
        "generated_at": decision_package.get("generated_at"),
        "source_policy": decision_package.get("policy"),
        "summary": closeout_summary,
        "lane_receipt": {
            "receipt_id": receipt_id,
            "stage": "P3_direct_mapping_candidate_decision_lane_closeout",
            "status": result,
            "receipt_status": (
                "candidate_decision_lane_receipt_ready"
                if decisions
                else "candidate_decision_lane_receipt_waiting_for_candidates"
            ),
            "payload_sha256": receipt_sha,
            "source_fingerprint": source_fingerprint,
            "materialize_artifacts": bool(materialize_artifacts),
            "requires_production_version_truth": True,
        },
        "receipt_replay": {
            "stage": "P3_direct_mapping_candidate_decision_lane_receipt_replay",
            "passed": replay_verified,
            "source_fingerprint": source_fingerprint,
            "receipt_fingerprint": receipt_fingerprint,
            "payload_sha256": receipt_sha,
            "writes_database": False,
        },
        "drift_verifier": {
            "stage": "P3_direct_mapping_candidate_decision_lane_drift_verifier",
            "status": "verified" if drift_count == 0 else "drift_detected",
            "drift_count": drift_count,
            "source_policy": decision_package.get("policy"),
            "writes_database": False,
        },
        "product_readiness": {
            "status": product_status,
            "next_machine_action": next_machine_action,
            "primary_human_gate_count": 0,
            "automation_policy": {
                "primary_flow": "ai_controlled",
                "manual_review_mode": "exception_only",
                "machine_verifiable_evidence": True,
            },
            "ready_for_next_automation": product_status == "ready_for_next_automation",
            "writes_database": False,
        },
        "receipt_artifact": receipt_artifact,
        "materialized_artifacts": materialized_artifacts,
        "post_receipt_artifact_verifier": {
            "expected_sha256": receipt_sha,
            "actual_sha256": actual_sha,
            "hash_match": receipt_hash_match,
            "writes_database": False,
        },
        "source_decision_summary": summary,
        "checks": checks,
        "check_count": len(checks),
        "all_checks_passed": all(check.get("passed") is True for check in checks),
        "next_actions": [
            "Run controlled read-only search when the lane is waiting for candidates.",
            "Route auto-compare decisions to no-write receipts before persistence.",
            "Route machine-review decisions to AI auto-resolution artifacts and closeout receipts.",
        ],
        "safety": safety,
    }


def build_pchome_direct_mapping_candidate_exception_auto_resolution_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Build a no-write auto-resolution package for machine-review candidate exceptions."""
    decision_package = build_pchome_direct_mapping_candidate_decision_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = decision_package.get("decision_package") or {}
    exception_receipts = list(package.get("machine_review_exception_receipts") or [])
    artifacts = list(package.get("machine_review_exception_auto_resolution_artifacts") or [])
    summary = _summarize_exception_auto_resolution_artifacts(artifacts)

    selected_direct_count = int((decision_package.get("summary") or {}).get("selected_direct_mapping_count") or 0)
    candidate_decision_count = int((decision_package.get("summary") or {}).get("candidate_decision_count") or 0)
    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif artifacts:
        result = "DIRECT_MAPPING_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
    elif candidate_decision_count:
        result = "DIRECT_MAPPING_CANDIDATE_EXCEPTIONS_CLEAR"
    else:
        result = "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"

    return {
        "policy": DIRECT_MAPPING_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY,
        "result": result,
        "success": bool(decision_package.get("success")),
        "generated_at": decision_package.get("generated_at"),
        "source_policy": decision_package.get("policy"),
        "stats": decision_package.get("stats") or {},
        "backlog": decision_package.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((decision_package.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": selected_direct_count,
            "candidate_decision_count": candidate_decision_count,
            "machine_review_exception_receipt_count": len(exception_receipts),
            **summary,
        },
        "auto_resolution_package": {
            "stage": "P2_machine_verifiable_exception_auto_resolution",
            "execute_search": bool(execute_search),
            "exception_receipts": exception_receipts,
            "auto_resolution_artifacts": artifacts,
            "resolution_mode": "ai_controlled_read_only",
        },
        "upstream_decision_summary": decision_package.get("summary") or {},
        "next_actions": [
            "Use variant_bundle_discriminator and named_candidate_evidence_delta before retry search.",
            "Use unit_basis_search_expansion for hard-veto unit candidates before another candidate decision package.",
            "Only route resolved candidates to no-write receipt and verifier packages before persistence.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_candidate_exception_resolution_closeout_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Close out candidate exception auto-resolution artifacts into retry-ready receipts."""
    auto_resolution = build_pchome_direct_mapping_candidate_exception_auto_resolution_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = auto_resolution.get("auto_resolution_package") or {}
    artifacts = list(package.get("auto_resolution_artifacts") or [])
    closeout_receipts = _build_candidate_exception_resolution_closeout_receipts(
        artifacts,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    closeout_summary = _summarize_exception_resolution_closeout_receipts(closeout_receipts)
    selected_direct_count = int((auto_resolution.get("summary") or {}).get("selected_direct_mapping_count") or 0)
    artifact_count = int((auto_resolution.get("summary") or {}).get("exception_auto_resolution_artifact_count") or 0)

    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif closeout_receipts:
        result = "DIRECT_MAPPING_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
    elif artifact_count:
        result = "DIRECT_MAPPING_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
    else:
        result = "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"

    return {
        "policy": DIRECT_MAPPING_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY,
        "result": result,
        "success": bool(auto_resolution.get("success")),
        "generated_at": auto_resolution.get("generated_at"),
        "source_policy": auto_resolution.get("policy"),
        "stats": auto_resolution.get("stats") or {},
        "backlog": auto_resolution.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((auto_resolution.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": selected_direct_count,
            "candidate_decision_count": int((auto_resolution.get("summary") or {}).get("candidate_decision_count") or 0),
            "machine_review_exception_receipt_count": int(
                (auto_resolution.get("summary") or {}).get("machine_review_exception_receipt_count") or 0
            ),
            "exception_auto_resolution_artifact_count": artifact_count,
            **closeout_summary,
        },
        "closeout_package": {
            "stage": "P2_machine_verifiable_exception_resolution_closeout",
            "execute_search": bool(execute_search),
            "execute_retry_search": bool(execute_retry_search),
            "closeout_receipts": closeout_receipts,
            "resolution_mode": "ai_controlled_read_only",
        },
        "upstream_auto_resolution_summary": auto_resolution.get("summary") or {},
        "next_actions": [
            "Feed retry_search candidates back into the candidate decision package when retry_candidate_count is nonzero.",
            "Feed evidence_delta closeouts into no-write verifier receipts before any persistence.",
            "Keep database writes behind controlled apply, rollback, and production readback.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_retry_search": bool(execute_retry_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_retry_candidate_decision_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Route retry-search candidates back into machine decisions and no-write verifier receipts."""
    closeout = build_pchome_direct_mapping_candidate_exception_resolution_closeout_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    closeout_package = closeout.get("closeout_package") or {}
    closeout_receipts = list(closeout_package.get("closeout_receipts") or [])
    retry_candidates = _retry_candidates_from_closeout_receipts(closeout_receipts)
    try:
        effective_min_score = max(0.35, min(float(min_score), 0.95))
    except (TypeError, ValueError):
        effective_min_score = 0.45

    retry_decisions = [
        _build_candidate_decision_envelope(candidate, min_score=effective_min_score)
        for candidate in retry_candidates
    ]
    no_write_decisions = [
        decision
        for decision in retry_decisions
        if decision.get("decision") == "route_to_no_write_auto_compare_receipt"
    ]
    machine_review_decisions = [
        decision
        for decision in retry_decisions
        if decision.get("decision") == "route_to_machine_review_decision"
    ]
    no_write_verifier_receipts = [
        _build_no_write_auto_compare_verifier_receipt(decision)
        for decision in no_write_decisions
    ]
    machine_review_exception_receipts = [
        _build_candidate_exception_receipt(decision)
        for decision in machine_review_decisions
    ]

    selected_direct_count = int((closeout.get("summary") or {}).get("selected_direct_mapping_count") or 0)
    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif retry_decisions:
        result = "DIRECT_MAPPING_RETRY_CANDIDATE_DECISION_PACKAGE_READY"
    elif int((closeout.get("summary") or {}).get("retry_search_ready_count") or 0):
        result = "WAITING_FOR_RETRY_CANDIDATES"
    else:
        result = "WAITING_FOR_EXCEPTION_RESOLUTION_CLOSEOUT"

    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_DECISION_PACKAGE_POLICY,
        "result": result,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "backlog": closeout.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((closeout.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": selected_direct_count,
            "exception_resolution_closeout_receipt_count": int(
                (closeout.get("summary") or {}).get("exception_resolution_closeout_receipt_count") or 0
            ),
            "retry_candidate_count": len(retry_candidates),
            "retry_candidate_decision_count": len(retry_decisions),
            "retry_no_write_verifier_input_count": len(no_write_verifier_receipts),
            "retry_machine_review_exception_count": len(machine_review_exception_receipts),
            "ready_for_no_write_verifier_count": sum(
                1 for receipt in no_write_verifier_receipts if receipt.get("ready_for_no_write_verifier")
            ),
            "ready_for_controlled_apply_count": 0,
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "retry_candidate_decision_package": {
            "stage": "P2_retry_candidate_machine_decision",
            "execute_search": bool(execute_search),
            "execute_retry_search": bool(execute_retry_search),
            "retry_candidates": retry_candidates,
            "retry_candidate_decisions": retry_decisions,
            "no_write_verifier_receipts": no_write_verifier_receipts,
            "machine_review_exception_receipts": machine_review_exception_receipts,
            "manual_review_mode": "exception_only",
        },
        "upstream_closeout_summary": closeout.get("summary") or {},
        "next_actions": [
            "Send ready no-write verifier receipts into verifier artifact preview before any persistence.",
            "Route retry machine-review exceptions back through exception auto-resolution.",
            "Only controlled apply can reduce direct_mapping_count after verifier, rollback, and production readback pass.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_retry_search": bool(execute_retry_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Build retry-exception auto-resolution artifacts without routing to human review."""
    retry_package = build_pchome_direct_mapping_retry_candidate_decision_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = retry_package.get("retry_candidate_decision_package") or {}
    retry_exception_receipts = list(package.get("machine_review_exception_receipts") or [])
    artifacts = _build_candidate_exception_auto_resolution_artifacts(retry_exception_receipts)
    artifact_summary = _summarize_exception_auto_resolution_artifacts(artifacts)

    selected_direct_count = int((retry_package.get("summary") or {}).get("selected_direct_mapping_count") or 0)
    retry_decision_count = int((retry_package.get("summary") or {}).get("retry_candidate_decision_count") or 0)
    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif artifacts:
        result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
    elif retry_decision_count:
        result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTIONS_CLEAR"
    else:
        result = "WAITING_FOR_RETRY_CANDIDATE_DECISIONS"

    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY,
        "result": result,
        "success": bool(retry_package.get("success")),
        "generated_at": retry_package.get("generated_at"),
        "source_policy": retry_package.get("policy"),
        "stats": retry_package.get("stats") or {},
        "backlog": retry_package.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((retry_package.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": selected_direct_count,
            "retry_candidate_count": int((retry_package.get("summary") or {}).get("retry_candidate_count") or 0),
            "retry_candidate_decision_count": retry_decision_count,
            "retry_no_write_verifier_input_count": int(
                (retry_package.get("summary") or {}).get("retry_no_write_verifier_input_count") or 0
            ),
            "retry_machine_review_exception_count": len(retry_exception_receipts),
            "retry_exception_auto_resolution_artifact_count": len(artifacts),
            "ready_for_no_write_verifier_count": int(
                (retry_package.get("summary") or {}).get("ready_for_no_write_verifier_count") or 0
            ),
            **artifact_summary,
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "retry_exception_auto_resolution_package": {
            "stage": "P2_retry_candidate_exception_auto_resolution",
            "execute_search": bool(execute_search),
            "execute_retry_search": bool(execute_retry_search),
            "retry_machine_review_exception_receipts": retry_exception_receipts,
            "retry_exception_auto_resolution_artifacts": artifacts,
            "resolution_mode": "ai_controlled_read_only",
            "manual_review_mode": "exception_only",
        },
        "upstream_retry_decision_summary": retry_package.get("summary") or {},
        "next_actions": [
            "Feed retry exception artifacts into a retry exception closeout package before another search cycle.",
            "Send ready no-write verifier receipts into verifier artifact preview before any persistence.",
            "Keep database writes behind controlled apply, rollback, verifier, and production readback.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_retry_search": bool(execute_retry_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Close out retry-candidate exception artifacts into machine-verifiable receipts."""
    auto_resolution = build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = auto_resolution.get("retry_exception_auto_resolution_package") or {}
    artifacts = list(package.get("retry_exception_auto_resolution_artifacts") or [])
    closeout_receipts = _build_candidate_exception_resolution_closeout_receipts(
        artifacts,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    closeout_summary = _summarize_exception_resolution_closeout_receipts(closeout_receipts)

    selected_direct_count = int((auto_resolution.get("summary") or {}).get("selected_direct_mapping_count") or 0)
    artifact_count = int(
        (auto_resolution.get("summary") or {}).get("retry_exception_auto_resolution_artifact_count") or 0
    )
    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif closeout_receipts:
        result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
    elif artifact_count:
        result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
    else:
        result = "WAITING_FOR_RETRY_CANDIDATE_EXCEPTIONS"

    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY,
        "result": result,
        "success": bool(auto_resolution.get("success")),
        "generated_at": auto_resolution.get("generated_at"),
        "source_policy": auto_resolution.get("policy"),
        "stats": auto_resolution.get("stats") or {},
        "backlog": auto_resolution.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((auto_resolution.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": selected_direct_count,
            "upstream_retry_candidate_count": int(
                (auto_resolution.get("summary") or {}).get("retry_candidate_count") or 0
            ),
            "retry_candidate_decision_count": int(
                (auto_resolution.get("summary") or {}).get("retry_candidate_decision_count") or 0
            ),
            "retry_machine_review_exception_count": int(
                (auto_resolution.get("summary") or {}).get("retry_machine_review_exception_count") or 0
            ),
            "retry_exception_auto_resolution_artifact_count": artifact_count,
            "retry_exception_resolution_closeout_receipt_count": len(closeout_receipts),
            **closeout_summary,
            "retry_exception_closeout_retry_candidate_count": closeout_summary.get("retry_candidate_count", 0),
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "retry_exception_resolution_closeout_package": {
            "stage": "P2_retry_candidate_exception_resolution_closeout",
            "execute_search": bool(execute_search),
            "execute_retry_search": bool(execute_retry_search),
            "closeout_receipts": closeout_receipts,
            "resolution_mode": "ai_controlled_read_only",
            "manual_review_mode": "exception_only",
        },
        "upstream_retry_exception_auto_resolution_summary": auto_resolution.get("summary") or {},
        "next_actions": [
            "Route evidence-delta closeouts into no-write verifier input when identity delta is resolved.",
            "Feed retry-search candidates back into retry candidate decision package when candidate_count is nonzero.",
            "Keep database writes behind controlled apply, rollback, verifier, and production readback.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_retry_search": bool(execute_retry_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_input_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Turn retry exception closeout receipts into no-write verifier inputs."""
    closeout = build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = closeout.get("retry_exception_resolution_closeout_package") or {}
    closeout_receipts = list(package.get("closeout_receipts") or [])
    verifier_receipts = _build_exception_closeout_no_write_verifier_receipts(closeout_receipts)
    verifier_summary = _summarize_exception_closeout_no_write_verifier_receipts(verifier_receipts)

    selected_direct_count = int((closeout.get("summary") or {}).get("selected_direct_mapping_count") or 0)
    closeout_count = int((closeout.get("summary") or {}).get("retry_exception_resolution_closeout_receipt_count") or 0)
    ready_count = int(verifier_summary.get("ready_closeout_no_write_verifier_input_count") or 0)
    if not selected_direct_count:
        result = "NO_DIRECT_MAPPING_TARGETS"
    elif ready_count:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_INPUT_READY"
    elif closeout_count:
        result = "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_CLEARANCE"
    else:
        result = "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_RECEIPTS"

    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_INPUT_POLICY,
        "result": result,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "backlog": closeout.get("backlog") or {},
        "summary": {
            "direct_mapping_count": int((closeout.get("summary") or {}).get("direct_mapping_count") or 0),
            "selected_direct_mapping_count": selected_direct_count,
            "retry_exception_resolution_closeout_receipt_count": closeout_count,
            "retry_exception_auto_resolution_artifact_count": int(
                (closeout.get("summary") or {}).get("retry_exception_auto_resolution_artifact_count") or 0
            ),
            "retry_machine_review_exception_count": int(
                (closeout.get("summary") or {}).get("retry_machine_review_exception_count") or 0
            ),
            **verifier_summary,
            "ready_for_controlled_apply_count": 0,
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "retry_exception_closeout_verifier_input_package": {
            "stage": "P2_retry_exception_closeout_no_write_verifier_input",
            "execute_search": bool(execute_search),
            "execute_retry_search": bool(execute_retry_search),
            "closeout_receipts": closeout_receipts,
            "no_write_verifier_receipts": verifier_receipts,
            "verifier_mode": "machine_verifiable_no_write",
            "manual_review_mode": "exception_only",
        },
        "upstream_retry_exception_closeout_summary": closeout.get("summary") or {},
        "next_actions": [
            "Feed ready no-write verifier inputs into verifier artifact preview before persistence.",
            "Route blocked verifier inputs back to retry candidate decision or exception closeout based on verification checks.",
            "Keep database writes behind controlled apply, rollback, verifier, and production readback.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_retry_search": bool(execute_retry_search),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def _retry_exception_closeout_verifier_artifact_preview_id(verifier_package: dict[str, Any]) -> str:
    payload = {
        "policy": verifier_package.get("policy") or "",
        "result": verifier_package.get("result") or "",
        "summary": verifier_package.get("summary") or {},
        "source_policy": verifier_package.get("source_policy") or "",
    }
    digest = hashlib.sha256(
        json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    return f"pchome-retry-closeout-verifier-artifacts-{digest[:16]}"


def build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
) -> dict[str, Any]:
    """Preview no-write verifier artifacts for retry exception closeout inputs."""
    verifier_package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_input_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    package = verifier_package.get("retry_exception_closeout_verifier_input_package") or {}
    verifier_receipts = list(package.get("no_write_verifier_receipts") or [])
    ready_receipts = [
        receipt
        for receipt in verifier_receipts
        if receipt.get("receipt_status") == "NO_WRITE_VERIFIER_INPUT_READY"
        and receipt.get("ready_for_no_write_verifier")
    ]
    blocked_receipts = [receipt for receipt in verifier_receipts if receipt not in ready_receipts]
    summary = verifier_package.get("summary") or {}
    preview_ready = bool(ready_receipts) and not blocked_receipts
    preview_status = (
        "DIRECT_MAPPING_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW_READY"
        if preview_ready
        else (
            "DIRECT_MAPPING_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW_PARTIAL"
            if ready_receipts
            else "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_INPUTS"
        )
    )
    preview_id = _retry_exception_closeout_verifier_artifact_preview_id(verifier_package)
    artifact_schemas = [
        {
            "key": "retry_exception_closeout_verifier_input_artifact",
            "artifact_type": "no_write_verifier_input_receipts",
            "artifact_path_template": "artifacts/pchome_growth/retry_exception_closeout/verifier_inputs/{run_id}.json",
            "source_receipt_count": len(ready_receipts),
            "required_fields": [
                "run_id",
                "preview_id",
                "no_write_verifier_receipts",
                "source_closeout_receipt_ids",
                "verification_checks",
                "created_at",
                "safety",
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "writes_database": False,
        },
        {
            "key": "retry_exception_identity_readback_artifact",
            "artifact_type": "identity_readback_plan",
            "artifact_path_template": "artifacts/pchome_growth/retry_exception_closeout/identity_readback/{run_id}.json",
            "source_receipt_count": len(ready_receipts),
            "required_fields": [
                "run_id",
                "preview_id",
                "target_pchome_product_ids",
                "momo_product_ids",
                "identity_delta_status",
                "created_at",
                "safety",
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "writes_database": False,
        },
        {
            "key": "retry_exception_controlled_apply_preflight_artifact",
            "artifact_type": "controlled_apply_preflight",
            "artifact_path_template": "artifacts/pchome_growth/retry_exception_closeout/controlled_apply_preflight/{run_id}.json",
            "source_receipt_count": len(ready_receipts),
            "required_fields": [
                "run_id",
                "preview_id",
                "ready_no_write_verifier_input_count",
                "blocked_no_write_verifier_input_count",
                "rollback_plan_required",
                "production_readback_required",
                "created_at",
                "safety",
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "writes_database": False,
        },
    ]
    generation_steps = [
        {
            "name": "create_retry_exception_verifier_run_id",
            "run_id_template": "pchome-retry-closeout-verifier-{utc_timestamp}-{preview_digest}",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "render_no_write_verifier_input_artifact_schema",
            "artifact_key": "retry_exception_closeout_verifier_input_artifact",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "render_identity_readback_artifact_schema",
            "artifact_key": "retry_exception_identity_readback_artifact",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "render_controlled_apply_preflight_artifact_schema",
            "artifact_key": "retry_exception_controlled_apply_preflight_artifact",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "link_artifacts_to_retry_exception_closeout_verifier_inputs",
            "source_ready_receipt_count": len(ready_receipts),
            "required": True,
            "writes_artifact_in_preview": False,
        },
    ]
    verifier_manifest = {
        "pre_apply_checks": [
            "production_truth_fresh_within_300_seconds",
            "all_ready_no_write_verifier_inputs_have_subject",
            "retry_candidate_pending_count_is_zero",
            "blocked_verifier_input_count_is_zero",
            "database_write_locked",
        ],
        "artifact_integrity_checks": [
            "all_artifacts_include_run_id",
            "all_artifacts_include_preview_id",
            "all_source_receipts_have_verification_checks",
            "controlled_apply_preflight_references_rollback_and_readback",
        ],
        "post_preview_checks": [
            "ready_inputs_can_enter_verifier_artifact_preview",
            "no_artifact_written_in_preview",
            "no_database_write_in_preview",
        ],
        "failure_handlers": [
            "route_blocked_inputs_back_to_retry_candidate_decision",
            "route_missing_identity_back_to_exception_closeout",
            "abort_controlled_apply_if_artifact_integrity_fails",
        ],
        "verifier_check_count": 15,
        "executes_in_preview": False,
        "writes_artifact_in_preview": False,
        "writes_database": False,
    }

    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW_POLICY,
        "result": preview_status,
        "success": bool(verifier_package.get("success")),
        "generated_at": verifier_package.get("generated_at"),
        "source_policy": verifier_package.get("policy"),
        "stats": verifier_package.get("stats") or {},
        "backlog": verifier_package.get("backlog") or {},
        "summary": {
            "verifier_artifact_preview_ready_count": 1 if preview_ready else 0,
            "closeout_no_write_verifier_input_count": int(
                summary.get("closeout_no_write_verifier_input_count") or 0
            ),
            "ready_closeout_no_write_verifier_input_count": len(ready_receipts),
            "blocked_closeout_no_write_verifier_input_count": len(blocked_receipts),
            "retry_candidate_pending_count": int(summary.get("retry_candidate_pending_count") or 0),
            "artifact_schema_count": len(artifact_schemas),
            "artifact_generation_step_count": len(generation_steps),
            "verifier_manifest_check_count": verifier_manifest["verifier_check_count"],
            "writes_artifact_count": 0,
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "retry_exception_closeout_verifier_artifact_preview": {
            "preview_id": preview_id,
            "stage": "P2_retry_exception_closeout_verifier_artifact_preview",
            "status": preview_status,
            "ready_for_future_artifact_generation": preview_ready,
            "ready_to_write_artifacts_now": False,
            "ready_for_controlled_apply_now": False,
            "source_ready_receipt_count": len(ready_receipts),
            "source_blocked_receipt_count": len(blocked_receipts),
            "writes_artifact_in_preview": False,
            "writes_database_in_preview": False,
            "manual_review_mode": "exception_only",
        },
        "artifact_schemas": artifact_schemas,
        "artifact_generation_plan": {
            "mode": "future_controlled_apply_run_only",
            "generation_steps": generation_steps,
            "generation_step_count": len(generation_steps),
            "writes_artifact_in_preview": False,
            "writes_database": False,
        },
        "verifier_manifest": verifier_manifest,
        "source_ready_no_write_verifier_receipts": ready_receipts,
        "source_blocked_no_write_verifier_receipts": blocked_receipts,
        "source_verifier_input_summary": summary,
        "next_actions": [
            "Use ready artifact preview as the input to controlled apply preflight only after fresh production truth.",
            "Keep artifact writing disabled in preview; future apply run must write artifacts with rollback and readback.",
            "Route any blocked verifier inputs back to retry candidate decision or exception closeout automatically.",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_retry_search": bool(execute_retry_search),
            "writes_artifact_in_preview": False,
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def _retry_exception_closeout_verifier_artifact_run_id(preview_package: dict[str, Any]) -> str:
    preview = preview_package.get("retry_exception_closeout_verifier_artifact_preview") or {}
    payload = {
        "preview_id": preview.get("preview_id") or "",
        "summary": preview_package.get("summary") or {},
        "artifact_schema_keys": [
            schema.get("key")
            for schema in preview_package.get("artifact_schemas") or []
        ],
    }
    digest = hashlib.sha256(
        json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    return f"pchome-retry-closeout-verifier-run-{digest[:16]}"




def _build_retry_exception_verifier_artifact_payloads(
    preview_package: dict[str, Any],
    run_id: str,
) -> list[dict[str, Any]]:
    preview = preview_package.get("retry_exception_closeout_verifier_artifact_preview") or {}
    ready_receipts = list(preview_package.get("source_ready_no_write_verifier_receipts") or [])
    blocked_receipts = list(preview_package.get("source_blocked_no_write_verifier_receipts") or [])
    schemas_by_key = {
        schema.get("key"): schema
        for schema in preview_package.get("artifact_schemas") or []
    }
    subjects = [receipt.get("subject") or {} for receipt in ready_receipts]
    target_ids = sorted(
        {
            str(subject.get("target_pchome_product_id"))
            for subject in subjects
            if subject.get("target_pchome_product_id")
        }
    )
    momo_ids = sorted(
        {
            str(subject.get("momo_product_id") or subject.get("product_id"))
            for subject in subjects
            if subject.get("momo_product_id") or subject.get("product_id")
        }
    )
    common = {
        "run_id": run_id,
        "preview_id": preview.get("preview_id"),
        "source_policy": preview_package.get("policy"),
        "created_from": "retry_exception_closeout_verifier_artifact_preview",
        "created_at": run_id,
        "safety": {
            "writes_database": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "requires_production_version_truth": True,
        },
    }
    payloads = [
        {
            **common,
            "artifact_key": "retry_exception_closeout_verifier_input_artifact",
            "no_write_verifier_receipts": ready_receipts,
            "source_closeout_receipt_ids": [
                receipt.get("source_closeout_receipt_id")
                for receipt in ready_receipts
                if receipt.get("source_closeout_receipt_id")
            ],
            "verification_checks": [
                {
                    "receipt_id": receipt.get("receipt_id"),
                    "checks": receipt.get("verification_checks") or [],
                }
                for receipt in ready_receipts
            ],
            "blocked_no_write_verifier_receipts": blocked_receipts,
        },
        {
            **common,
            "artifact_key": "retry_exception_identity_readback_artifact",
            "target_pchome_product_ids": target_ids,
            "momo_product_ids": momo_ids,
            "identity_delta_status": "ready" if ready_receipts and not blocked_receipts else "blocked",
            "source_receipt_ids": [
                receipt.get("receipt_id")
                for receipt in ready_receipts
                if receipt.get("receipt_id")
            ],
        },
        {
            **common,
            "artifact_key": "retry_exception_controlled_apply_preflight_artifact",
            "ready_no_write_verifier_input_count": len(ready_receipts),
            "blocked_no_write_verifier_input_count": len(blocked_receipts),
            "rollback_plan_required": True,
            "production_readback_required": True,
            "ready_for_controlled_apply_now": False,
            "next_gate": "retry_exception_controlled_apply_preflight",
        },
    ]
    artifacts: list[dict[str, Any]] = []
    for payload in payloads:
        key = payload["artifact_key"]
        schema = schemas_by_key.get(key) or {}
        relative_path = str(schema.get("artifact_path_template") or "").format(run_id=run_id)
        artifact_bytes = _canonical_retry_exception_artifact_bytes(payload)
        artifacts.append({
            "key": key,
            "artifact_type": schema.get("artifact_type") or key,
            "relative_path": relative_path,
            "payload_sha256": hashlib.sha256(artifact_bytes).hexdigest(),
            "byte_count": len(artifact_bytes),
            "payload": payload,
            "materialized": False,
            "writes_database": False,
        })
    return artifacts


def build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
    materialize_artifacts: bool = False,
    artifact_root: str | Path | None = None,
) -> dict[str, Any]:
    """Build and optionally materialize verifier artifacts without database writes."""
    preview_package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
    )
    preview = preview_package.get("retry_exception_closeout_verifier_artifact_preview") or {}
    materialization_ready = bool(preview.get("ready_for_future_artifact_generation"))
    run_id = _retry_exception_closeout_verifier_artifact_run_id(preview_package)
    artifact_payloads = _build_retry_exception_verifier_artifact_payloads(preview_package, run_id)
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    materialized_artifacts: list[dict[str, Any]] = []
    if materialize_artifacts and materialization_ready:
        for artifact in artifact_payloads:
            target_path = _resolve_retry_exception_artifact_path(root, artifact["relative_path"])
            target_path.parent.mkdir(parents=True, exist_ok=True)
            target_path.write_bytes(_canonical_retry_exception_artifact_bytes(artifact["payload"]))
            materialized_artifacts.append({
                "key": artifact["key"],
                "relative_path": artifact["relative_path"],
                "absolute_path": str(target_path),
                "payload_sha256": artifact["payload_sha256"],
                "written_byte_count": target_path.stat().st_size,
                "writes_database": False,
            })
            artifact["materialized"] = True
            artifact["absolute_path"] = str(target_path)

    if not materialization_ready:
        result = "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW"
    elif materialize_artifacts and len(materialized_artifacts) == len(artifact_payloads):
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACTS_MATERIALIZED"
    elif materialize_artifacts:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACT_MATERIALIZATION_PARTIAL"
    else:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACT_MATERIALIZATION_READY"

    rollback_steps = [
        {
            "key": artifact["key"],
            "action": "delete_materialized_artifact_file",
            "relative_path": artifact["relative_path"],
            "executes_in_package": False,
            "writes_database": False,
        }
        for artifact in artifact_payloads
    ]
    verifier_checks = [
        "artifact_payload_count_matches_schema_count",
        "all_artifact_payloads_include_run_id",
        "all_artifact_payloads_include_preview_id",
        "all_payload_hashes_are_sha256",
        "materialized_artifact_count_matches_payload_count_when_enabled",
        "rollback_plan_references_all_artifacts",
        "controlled_apply_preflight_artifact_present",
        "production_truth_required_before_next_apply",
        "database_write_count_is_zero",
    ]
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_MATERIALIZATION_POLICY,
        "result": result,
        "success": bool(preview_package.get("success")),
        "generated_at": preview_package.get("generated_at"),
        "source_policy": preview_package.get("policy"),
        "stats": preview_package.get("stats") or {},
        "backlog": preview_package.get("backlog") or {},
        "summary": {
            "artifact_materialization_ready_count": 1 if materialization_ready else 0,
            "artifact_payload_count": len(artifact_payloads),
            "artifact_materialized_count": len(materialized_artifacts),
            "artifact_write_count": len(materialized_artifacts),
            "ready_closeout_no_write_verifier_input_count": int(
                (preview_package.get("summary") or {}).get("ready_closeout_no_write_verifier_input_count") or 0
            ),
            "blocked_closeout_no_write_verifier_input_count": int(
                (preview_package.get("summary") or {}).get("blocked_closeout_no_write_verifier_input_count") or 0
            ),
            "rollback_step_count": len(rollback_steps),
            "post_materialization_verifier_check_count": len(verifier_checks),
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "artifact_materialization_package": {
            "run_id": run_id,
            "source_preview_id": preview.get("preview_id"),
            "stage": "P2_retry_exception_closeout_verifier_artifact_materialization",
            "status": result,
            "materialize_artifacts": bool(materialize_artifacts),
            "artifact_root": str(root),
            "ready_for_artifact_write": materialization_ready,
            "ready_for_controlled_apply_now": False,
            "writes_database": False,
            "rollback_action": "delete_materialized_artifact_files",
        },
        "artifact_payloads": artifact_payloads,
        "materialized_artifacts": materialized_artifacts,
        "rollback_plan": {
            "rollback_step_count": len(rollback_steps),
            "rollback_steps": rollback_steps,
            "executes_in_package": False,
            "writes_database": False,
        },
        "post_materialization_verifier": {
            "checks": verifier_checks,
            "check_count": len(verifier_checks),
            "executes_database_verifier": False,
            "writes_database": False,
        },
        "source_preview_summary": preview_package.get("summary") or {},
        "next_actions": [
            "Use materialized verifier artifacts as the only input to retry exception controlled apply preflight.",
            "Before any database persistence, require fresh production truth, rollback plan, and post-apply readback.",
            "If materialized artifacts must be reverted, delete the listed artifact files; no database rollback is needed.",
        ],
        "safety": {
            "ai_controlled_apply": True,
            "materialize_artifacts": bool(materialize_artifacts),
            "writes_artifact_count": len(materialized_artifacts),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_materialization": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def _retry_exception_artifact_required_fields(artifact_key: str) -> list[str]:
    fields_by_key = {
        "retry_exception_closeout_verifier_input_artifact": [
            "run_id",
            "preview_id",
            "no_write_verifier_receipts",
            "source_closeout_receipt_ids",
            "verification_checks",
            "created_at",
            "safety",
        ],
        "retry_exception_identity_readback_artifact": [
            "run_id",
            "preview_id",
            "target_pchome_product_ids",
            "momo_product_ids",
            "identity_delta_status",
            "created_at",
            "safety",
        ],
        "retry_exception_controlled_apply_preflight_artifact": [
            "run_id",
            "preview_id",
            "ready_no_write_verifier_input_count",
            "blocked_no_write_verifier_input_count",
            "rollback_plan_required",
            "production_readback_required",
            "created_at",
            "safety",
        ],
    }
    return fields_by_key.get(artifact_key, ["run_id", "preview_id", "safety"])


def _verify_retry_exception_materialized_artifact(
    root: Path,
    artifact: dict[str, Any],
    run_id: str,
    preview_id: str | None,
) -> dict[str, Any]:
    path = _resolve_retry_exception_artifact_path(root, str(artifact.get("relative_path") or ""))
    expected_sha = str(artifact.get("payload_sha256") or "")
    checks: list[dict[str, Any]] = [
        {"check": "artifact_relative_path_safe", "passed": not path.is_absolute() or str(path).startswith(str(root))},
        {"check": "artifact_file_exists", "passed": path.exists()},
    ]
    payload: dict[str, Any] = {}
    actual_sha = ""
    byte_count = 0
    json_valid = False
    if path.exists():
        artifact_bytes = path.read_bytes()
        byte_count = len(artifact_bytes)
        actual_sha = hashlib.sha256(artifact_bytes).hexdigest()
        try:
            payload = json.loads(artifact_bytes.decode("utf-8"))
            json_valid = isinstance(payload, dict)
        except (UnicodeDecodeError, json.JSONDecodeError):
            payload = {}
    required_fields = _retry_exception_artifact_required_fields(str(artifact.get("key") or ""))
    missing_fields = [field for field in required_fields if field not in payload]
    checks.extend([
        {"check": "artifact_sha256_matches_expected", "passed": bool(actual_sha) and actual_sha == expected_sha},
        {"check": "artifact_json_is_valid_object", "passed": json_valid},
        {"check": "required_fields_present", "passed": not missing_fields, "missing_fields": missing_fields},
        {"check": "run_id_matches_materialization", "passed": payload.get("run_id") == run_id},
        {"check": "preview_id_matches_materialization", "passed": payload.get("preview_id") == preview_id},
        {"check": "safety_writes_database_false", "passed": (payload.get("safety") or {}).get("writes_database") is False},
    ])
    if artifact.get("key") == "retry_exception_controlled_apply_preflight_artifact":
        checks.extend([
            {"check": "rollback_plan_required", "passed": payload.get("rollback_plan_required") is True},
            {"check": "production_readback_required", "passed": payload.get("production_readback_required") is True},
            {"check": "controlled_apply_not_enabled_directly", "passed": payload.get("ready_for_controlled_apply_now") is False},
        ])
    passed = all(check.get("passed") is True for check in checks)
    return {
        "key": artifact.get("key"),
        "relative_path": artifact.get("relative_path"),
        "absolute_path": str(path),
        "exists": path.exists(),
        "expected_sha256": expected_sha,
        "actual_sha256": actual_sha,
        "hash_match": bool(actual_sha) and actual_sha == expected_sha,
        "byte_count": byte_count,
        "required_field_count": len(required_fields),
        "missing_fields": missing_fields,
        "checks": checks,
        "check_count": len(checks),
        "passed": passed,
        "writes_database": False,
    }


def build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
    materialize_artifacts: bool = False,
    artifact_root: str | Path | None = None,
) -> dict[str, Any]:
    """Verify materialized retry exception artifacts before controlled apply preflight."""
    materialization_package = (
        build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_package(
            payload,
            batch_size=batch_size,
            execute_search=execute_search,
            execute_retry_search=execute_retry_search,
            limit_per_product=limit_per_product,
            max_terms_per_product=max_terms_per_product,
            min_score=min_score,
            search_func=search_func,
            materialize_artifacts=materialize_artifacts,
            artifact_root=artifact_root,
        )
    )
    materialization = materialization_package.get("artifact_materialization_package") or {}
    root = Path(materialization.get("artifact_root") or (Path.cwd() / "data"))
    run_id = str(materialization.get("run_id") or "")
    preview_id = materialization.get("source_preview_id")
    artifact_payloads = list(materialization_package.get("artifact_payloads") or [])
    artifact_readbacks = [
        _verify_retry_exception_materialized_artifact(root, artifact, run_id, preview_id)
        for artifact in artifact_payloads
    ]
    passed_count = sum(1 for readback in artifact_readbacks if readback.get("passed"))
    failed_count = len(artifact_readbacks) - passed_count
    hash_match_count = sum(1 for readback in artifact_readbacks if readback.get("hash_match"))
    missing_field_count = sum(len(readback.get("missing_fields") or []) for readback in artifact_readbacks)
    materialization_ready = bool(
        (materialization_package.get("summary") or {}).get("artifact_materialization_ready_count")
    )
    preflight_verified = bool(artifact_readbacks) and failed_count == 0 and materialization_ready
    result = (
        "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACT_PREFLIGHT_VERIFIED"
        if preflight_verified
        else (
            "WAITING_FOR_RETRY_EXCEPTION_VERIFIER_ARTIFACT_FILES"
            if materialization_ready
            else "WAITING_FOR_RETRY_EXCEPTION_VERIFIER_ARTIFACT_MATERIALIZATION"
        )
    )
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREFLIGHT_VERIFIER_POLICY,
        "result": result,
        "success": bool(materialization_package.get("success")),
        "generated_at": materialization_package.get("generated_at"),
        "source_policy": materialization_package.get("policy"),
        "stats": materialization_package.get("stats") or {},
        "backlog": materialization_package.get("backlog") or {},
        "summary": {
            "artifact_preflight_verifier_ready_count": 1 if preflight_verified else 0,
            "artifact_payload_count": len(artifact_payloads),
            "artifact_readback_count": len(artifact_readbacks),
            "artifact_readback_pass_count": passed_count,
            "artifact_readback_fail_count": failed_count,
            "artifact_hash_match_count": hash_match_count,
            "missing_required_field_count": missing_field_count,
            "ready_closeout_no_write_verifier_input_count": int(
                (materialization_package.get("summary") or {}).get("ready_closeout_no_write_verifier_input_count") or 0
            ),
            "rollback_step_count": int((materialization_package.get("summary") or {}).get("rollback_step_count") or 0),
            "controlled_apply_preflight_contract_count": 1 if preflight_verified else 0,
            "writes_artifact_count": int((materialization_package.get("summary") or {}).get("artifact_write_count") or 0),
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "artifact_preflight_verifier": {
            "run_id": run_id,
            "source_preview_id": preview_id,
            "source_materialization_status": materialization.get("status"),
            "stage": "P2_retry_exception_closeout_verifier_artifact_preflight_verifier",
            "status": result,
            "artifact_root": str(root),
            "ready_for_controlled_apply_preflight": preflight_verified,
            "ready_for_database_apply_now": False,
            "requires_fresh_production_truth_before_apply": True,
            "writes_database": False,
        },
        "artifact_readbacks": artifact_readbacks,
        "controlled_apply_preflight_contract": {
            "contract_ready": preflight_verified,
            "input_artifact_count": len(artifact_readbacks),
            "requires_rollback_plan": True,
            "requires_post_apply_readback": True,
            "requires_artifact_hash_match": True,
            "allows_database_write_now": False,
            "writes_database": False,
        },
        "source_materialization_summary": materialization_package.get("summary") or {},
        "next_actions": [
            "Feed verified artifacts into retry exception controlled apply preflight with production truth refresh.",
            "Abort apply if any artifact readback hash or required field check fails.",
            "Keep database writes disabled until the next controlled apply executor package passes rollback and readback gates.",
        ],
        "safety": {
            "ai_controlled_apply": True,
            "materialize_artifacts": bool(materialize_artifacts),
            "reads_artifact_files": True,
            "writes_artifact_count": int((materialization_package.get("summary") or {}).get("artifact_write_count") or 0),
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preflight_verifier": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def _retry_exception_controlled_apply_preflight_id(verifier_package: dict[str, Any]) -> str:
    verifier = verifier_package.get("artifact_preflight_verifier") or {}
    summary = verifier_package.get("summary") or {}
    payload = {
        "run_id": verifier.get("run_id") or "",
        "source_preview_id": verifier.get("source_preview_id") or "",
        "artifact_hash_match_count": summary.get("artifact_hash_match_count") or 0,
        "artifact_readback_pass_count": summary.get("artifact_readback_pass_count") or 0,
    }
    digest = hashlib.sha256(
        json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()
    return f"pchome-retry-exception-controlled-apply-preflight-{digest[:16]}"


def _load_retry_exception_artifact_payload(root: Path, readback: dict[str, Any]) -> dict[str, Any]:
    path = _resolve_retry_exception_artifact_path(root, str(readback.get("relative_path") or ""))
    if not path.exists():
        return {}
    try:
        loaded = json.loads(path.read_text(encoding="utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError):
        return {}
    return loaded if isinstance(loaded, dict) else {}


def _build_retry_exception_controlled_apply_selectors(verifier_input_payload: dict[str, Any]) -> list[dict[str, Any]]:
    selectors: list[dict[str, Any]] = []
    for receipt in verifier_input_payload.get("no_write_verifier_receipts") or []:
        subject = receipt.get("subject") or {}
        momo_product_id = subject.get("momo_product_id") or subject.get("product_id")
        target_pchome_product_id = subject.get("target_pchome_product_id")
        if not momo_product_id or not target_pchome_product_id:
            continue
        selectors.append({
            "selector_id": receipt.get("receipt_id"),
            "momo_product_id": momo_product_id,
            "momo_product_name": subject.get("momo_product_name"),
            "momo_price": subject.get("momo_price"),
            "target_pchome_product_id": target_pchome_product_id,
            "target_pchome_product_name": subject.get("pchome_product_name") or subject.get("target_pchome_name"),
            "target_match_score": subject.get("target_match_score"),
            "auto_compare_type": subject.get("auto_compare_type"),
            "source_closeout_receipt_id": receipt.get("source_closeout_receipt_id"),
            "source_artifact_id": receipt.get("source_artifact_id"),
            "source_decision_id": receipt.get("source_decision_id"),
            "ready_for_controlled_apply_preflight": True,
        })
    return selectors


def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_preflight_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
    materialize_artifacts: bool = False,
    artifact_root: str | Path | None = None,
) -> dict[str, Any]:
    """Build a machine-verifiable controlled apply preflight from verified retry artifacts."""
    verifier_package = (
        build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_package(
            payload,
            batch_size=batch_size,
            execute_search=execute_search,
            execute_retry_search=execute_retry_search,
            limit_per_product=limit_per_product,
            max_terms_per_product=max_terms_per_product,
            min_score=min_score,
            search_func=search_func,
            materialize_artifacts=materialize_artifacts,
            artifact_root=artifact_root,
        )
    )
    verifier = verifier_package.get("artifact_preflight_verifier") or {}
    verifier_ready = bool(verifier.get("ready_for_controlled_apply_preflight"))
    root = Path(verifier.get("artifact_root") or (Path.cwd() / "data"))
    readbacks = list(verifier_package.get("artifact_readbacks") or [])
    payload_by_key = {
        str(readback.get("key") or ""): _load_retry_exception_artifact_payload(root, readback)
        for readback in readbacks
        if readback.get("passed")
    }
    verifier_input_payload = payload_by_key.get("retry_exception_closeout_verifier_input_artifact") or {}
    selectors = _build_retry_exception_controlled_apply_selectors(verifier_input_payload)
    preflight_id = _retry_exception_controlled_apply_preflight_id(verifier_package)
    mutation_plan = [
        {
            "mutation_id": f"{preflight_id}-{index + 1:03d}",
            "action": "upsert_retry_exception_direct_mapping_candidate",
            "selector_id": selector.get("selector_id"),
            "momo_product_id": selector.get("momo_product_id"),
            "target_pchome_product_id": selector.get("target_pchome_product_id"),
            "write_mode": "future_controlled_executor_only",
            "executes_in_preflight": False,
            "writes_database": False,
        }
        for index, selector in enumerate(selectors)
    ]
    guard_checks = [
        {
            "check": "artifact_preflight_verifier_ready",
            "passed": verifier_ready,
        },
        {
            "check": "target_selector_count_positive",
            "passed": bool(selectors),
        },
        {
            "check": "all_artifact_readbacks_passed",
            "passed": int((verifier_package.get("summary") or {}).get("artifact_readback_fail_count") or 0) == 0,
        },
        {
            "check": "artifact_hashes_all_match",
            "passed": int((verifier_package.get("summary") or {}).get("artifact_hash_match_count") or 0) == len(readbacks),
        },
        {
            "check": "identity_readback_artifact_ready",
            "passed": (payload_by_key.get("retry_exception_identity_readback_artifact") or {}).get("identity_delta_status") == "ready",
        },
        {
            "check": "controlled_apply_artifact_requires_rollback",
            "passed": (payload_by_key.get("retry_exception_controlled_apply_preflight_artifact") or {}).get("rollback_plan_required") is True,
        },
        {
            "check": "controlled_apply_artifact_requires_post_apply_readback",
            "passed": (
                payload_by_key.get("retry_exception_controlled_apply_preflight_artifact") or {}
            ).get("production_readback_required") is True,
        },
        {
            "check": "preflight_does_not_execute_database_write",
            "passed": True,
        },
        {
            "check": "executor_still_requires_fresh_production_truth",
            "passed": True,
        },
    ]
    preflight_ready = all(check["passed"] for check in guard_checks)
    result = (
        "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_RETRY_EXCEPTION_ARTIFACT_PREFLIGHT_VERIFIER"
    )
    rollback_steps = [
        {
            "mutation_id": mutation.get("mutation_id"),
            "action": "delete_or_restore_retry_exception_mapping_candidate",
            "selector_id": mutation.get("selector_id"),
            "executes_in_preflight": False,
            "writes_database": False,
        }
        for mutation in mutation_plan
    ]
    readback_checks = [
        "mapping_candidate_exists_for_selector",
        "mapping_candidate_source_receipt_matches",
        "target_pchome_product_id_matches_selector",
        "momo_product_id_matches_selector",
        "post_apply_artifact_hashes_still_match",
    ]
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_PREFLIGHT_POLICY,
        "result": result,
        "success": bool(verifier_package.get("success")),
        "generated_at": verifier_package.get("generated_at"),
        "source_policy": verifier_package.get("policy"),
        "stats": verifier_package.get("stats") or {},
        "backlog": verifier_package.get("backlog") or {},
        "summary": {
            "controlled_apply_preflight_ready_count": 1 if preflight_ready else 0,
            "source_artifact_preflight_ready_count": int(
                (verifier_package.get("summary") or {}).get("artifact_preflight_verifier_ready_count") or 0
            ),
            "target_selector_count": len(selectors),
            "mutation_plan_count": len(mutation_plan),
            "rollback_step_count": len(rollback_steps),
            "post_apply_readback_check_count": len(readback_checks),
            "guard_check_count": len(guard_checks),
            "guard_pass_count": sum(1 for check in guard_checks if check.get("passed")),
            "guard_fail_count": sum(1 for check in guard_checks if not check.get("passed")),
            "writes_artifact_count": int((verifier_package.get("summary") or {}).get("writes_artifact_count") or 0),
            "executes_database_write_count": 0,
            "writes_database_count": 0,
            "persists_candidate_count": 0,
        },
        "controlled_apply_preflight": {
            "preflight_id": preflight_id,
            "run_id": verifier.get("run_id"),
            "source_preview_id": verifier.get("source_preview_id"),
            "stage": "P2_retry_exception_controlled_apply_preflight",
            "status": result,
            "artifact_root": str(root),
            "ready_for_controlled_apply_executor": preflight_ready,
            "ready_for_database_apply_now": False,
            "requires_fresh_production_truth_before_executor": True,
            "executes_database_write_in_preflight": False,
            "writes_database": False,
        },
        "target_selectors": selectors,
        "mutation_plan": {
            "mode": "dry_run_preflight_only",
            "mutation_plan_count": len(mutation_plan),
            "mutations": mutation_plan,
            "executes_in_preflight": False,
            "writes_database": False,
        },
        "rollback_plan": {
            "rollback_step_count": len(rollback_steps),
            "rollback_steps": rollback_steps,
            "executes_in_preflight": False,
            "writes_database": False,
        },
        "post_apply_readback_plan": {
            "readback_checks": readback_checks,
            "readback_check_count": len(readback_checks),
            "executes_in_preflight": False,
            "writes_database": False,
        },
        "executor_guard": {
            "guard_checks": guard_checks,
            "guard_check_count": len(guard_checks),
            "all_passed": preflight_ready,
            "requires_fresh_production_truth": True,
            "allows_database_write_now": False,
            "writes_database": False,
        },
        "source_artifact_preflight_summary": verifier_package.get("summary") or {},
        "next_actions": [
            "Feed this preflight into the retry exception controlled apply executor only after fresh production truth.",
            "Executor must write one receipt per selector and then run post-apply readback checks.",
            "Abort executor if any guard check, rollback plan, or artifact hash readback drifts.",
        ],
        "safety": {
            "ai_controlled_apply": True,
            "materialize_artifacts": bool(materialize_artifacts),
            "reads_artifact_files": True,
            "writes_artifact_count": int((verifier_package.get("summary") or {}).get("writes_artifact_count") or 0),
            "executes_database_write_in_preflight": False,
            "writes_database": False,
            "persists_candidate": False,
            "syncs_external_offers": False,
            "dispatches_telegram": False,
            "llm_calls_in_preflight": False,
            "gemini_allowed": False,
            "requires_production_version_truth": True,
        },
    }


def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_executor_package(
    payload: dict[str, Any],
    batch_size: int = 5,
    *,
    execute_search: bool = False,
    execute_retry_search: bool = False,
    limit_per_product: int = 8,
    max_terms_per_product: int = 5,
    min_score: float = 0.45,
    search_func: Any = None,
    materialize_artifacts: bool = False,
    artifact_root: str | Path | None = None,
    execute_apply: bool = False,
    engine: Any = None,
) -> dict[str, Any]:
    """Execute the verified retry exception controlled apply against pchome_product_matches."""
    preflight_package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_preflight_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        execute_retry_search=execute_retry_search,
        limit_per_product=limit_per_product,
        max_terms_per_product=max_terms_per_product,
        min_score=min_score,
        search_func=search_func,
        materialize_artifacts=materialize_artifacts,
        artifact_root=artifact_root,
    )
    return build_controlled_apply_executor_from_preflight(
        preflight_package,
        execute_apply=execute_apply,
        engine=engine,
        materialize_artifacts=materialize_artifacts,
        artifact_root=artifact_root,
    )






def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
    *,
    artifact_root: str | Path | None = None,
    run_id: str | None = None,
    engine: Any = None,
    source_receipt_replay: dict[str, Any] | None = None,
    materialize_artifacts: bool = False,
) -> dict[str, Any]:
    """Verify that applied PChome product matches still agree with the replay receipt."""
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    replay = source_receipt_replay or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
        artifact_root=root,
        run_id=run_id,
        materialize_artifacts=False,
        engine=engine,
    )
    return build_controlled_apply_drift_verifier_from_replay(
        replay,
        root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=source_receipt_replay,
        materialize_artifacts=materialize_artifacts,
    )




def _retry_exception_controlled_apply_drift_recovery_id(
    run_id: str,
    drift_items: list[dict[str, Any]],
) -> str:
    payload = {
        "run_id": run_id,
        "drift_items": drift_items,
    }
    digest = hashlib.sha256(
        json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()[:16]
    return f"pchome-retry-exception-controlled-apply-drift-recovery-{digest}"


def _build_retry_exception_drift_recovery_action(item: dict[str, Any], index: int) -> dict[str, Any]:
    momo_icode = str(item.get("momo_icode") or "").strip()
    expected_pchome_id = str(item.get("expected_pchome_id") or "").strip()
    actual_pchome_id = str(item.get("actual_pchome_id") or "").strip()
    selector_id = str(item.get("selector_id") or "").strip()
    action_id_payload = {
        "selector_id": selector_id,
        "momo_icode": momo_icode,
        "expected_pchome_id": expected_pchome_id,
        "actual_pchome_id": actual_pchome_id,
        "index": index,
    }
    action_id = "pchome-drift-recovery-action-" + hashlib.sha256(
        json.dumps(action_id_payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
    ).hexdigest()[:12]
    can_reapply = bool(momo_icode and expected_pchome_id)
    action_type = "reapply_expected_match" if can_reapply else "hold_for_selector_rebuild"
    return {
        "action_id": action_id,
        "selector_id": selector_id,
        "momo_icode": momo_icode,
        "expected_pchome_id": expected_pchome_id,
        "actual_pchome_id": actual_pchome_id,
        "expected_momo_name": item.get("expected_momo_name"),
        "actual_momo_name": item.get("actual_momo_name"),
        "action_type": action_type,
        "status": "ready_for_controlled_reapply" if can_reapply else "blocked_missing_selector_identity",
        "reason": (
            "current DB pchome_id differs from the machine receipt expected value"
            if can_reapply
            else "missing momo_icode or expected_pchome_id in receipt replay readback"
        ),
        "controlled_reapply_sql_shape": (
            "UPDATE pchome_product_matches "
            "SET pchome_id = :expected_pchome_id, advantage = 'ai_match' "
            "WHERE momo_icode = :momo_icode "
            "AND COALESCE(pchome_id, '') = :actual_pchome_id"
        ),
        "rollback_sql_shape": (
            "UPDATE pchome_product_matches "
            "SET pchome_id = :actual_pchome_id "
            "WHERE momo_icode = :momo_icode "
            "AND pchome_id = :expected_pchome_id"
        ),
        "selector_bindings": {
            "momo_icode": momo_icode,
            "expected_pchome_id": expected_pchome_id,
            "actual_pchome_id": actual_pchome_id,
        },
        "acceptance_gates": [
            "production_version_truth_passed_same_run",
            "receipt_replay_hash_matches_expected",
            "drift_verifier_result_is_drift_detected",
            "target_selector_matches_receipt_identity",
            "controlled_reapply_runs_in_check_mode_first",
            "post_reapply_drift_verifier_returns_zero_drift",
        ],
        "executes_in_package": False,
        "writes_database": False,
    }


def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_recovery_package(
    *,
    artifact_root: str | Path | None = None,
    run_id: str | None = None,
    engine: Any = None,
    source_receipt_replay: dict[str, Any] | None = None,
    source_drift_verifier: dict[str, Any] | None = None,
    materialize_artifacts: bool = False,
) -> dict[str, Any]:
    """Build a read-only rollback/re-apply recommendation package for drift items."""
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    replay = source_receipt_replay or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
        artifact_root=root,
        run_id=run_id,
        materialize_artifacts=False,
        engine=engine,
    )
    verifier = source_drift_verifier or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=replay,
        materialize_artifacts=False,
    )
    drift_items = list(verifier.get("drift_items") or [])
    recovery_actions = [
        _build_retry_exception_drift_recovery_action(item, index)
        for index, item in enumerate(drift_items, start=1)
    ]
    ready_actions = [
        item for item in recovery_actions
        if item.get("status") == "ready_for_controlled_reapply"
    ]
    replay_summary = replay.get("summary") or {}
    verifier_summary = verifier.get("summary") or {}
    run_id_value = (
        (verifier.get("drift_verifier") or {}).get("run_id")
        or (replay.get("receipt_replay") or {}).get("run_id")
        or run_id
        or ""
    )
    recovery_id = _retry_exception_controlled_apply_drift_recovery_id(run_id_value, drift_items)
    receipt_hash_match_count = int(replay_summary.get("executor_receipt_hash_match_count") or 0)
    drift_count = int(verifier_summary.get("drift_count") or 0)
    source_ready = (
        bool(replay)
        and bool(verifier)
        and not replay.get("missing_artifacts")
        and (receipt_hash_match_count > 0 or drift_count > 0)
    )

    if drift_count and ready_actions:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_PACKAGE_READY"
    elif drift_count:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_BLOCKED"
    elif verifier.get("result") == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIED":
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_NOT_REQUIRED"
    elif replay.get("missing_artifacts"):
        result = "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_ARTIFACTS"
    else:
        result = "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_BASELINE"

    summary = {
        "target_selector_count": int(verifier_summary.get("target_selector_count") or 0),
        "post_apply_readback_pass_count": int(verifier_summary.get("post_apply_readback_pass_count") or 0),
        "drift_count": drift_count,
        "drift_recovery_action_count": len(recovery_actions),
        "drift_reapply_ready_count": len(ready_actions),
        "drift_recovery_blocked_count": len(recovery_actions) - len(ready_actions),
        "receipt_hash_match_count": receipt_hash_match_count,
        "recovery_artifact_materialized_count": 0,
        "recovery_artifact_hash_match_count": 0,
        "writes_database_count": 0,
    }
    safety = {
        "ai_controlled_apply": True,
        "drift_recovery": True,
        "reads_artifact_files": True,
        "reads_database": engine is not None or bool(source_receipt_replay) or bool(source_drift_verifier),
        "writes_database": False,
        "writes_database_count": 0,
        "writes_artifact_count": 0,
        "syncs_external_offers": False,
        "dispatches_telegram": False,
        "gemini_allowed": False,
        "requires_production_version_truth": True,
    }
    dry_run_plan = {
        "mode": "controlled_reapply_check_mode_first",
        "ready": bool(ready_actions),
        "action_count": len(ready_actions),
        "executes_in_package": False,
        "writes_database": False,
        "post_apply_verifier": (
            "build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package"
        ),
    }
    rollback_plan = {
        "mode": "rollback_to_pre_reapply_actual_values",
        "rollback_action_count": len(ready_actions),
        "executes_in_package": False,
        "writes_database": False,
        "source": "current drift readbacks",
    }
    checks = [
        {"check": "source_receipt_replay_loaded", "passed": bool(replay)},
        {"check": "source_drift_verifier_loaded", "passed": bool(verifier)},
        {"check": "source_artifacts_ready", "passed": source_ready},
        {"check": "drift_items_match_summary", "passed": len(drift_items) == drift_count},
        {"check": "ready_actions_cover_detected_drift", "passed": (not drift_count) or len(ready_actions) == drift_count},
        {"check": "recovery_package_does_not_write_database", "passed": True},
    ]
    artifact_payload = {
        "artifact_key": "retry_exception_controlled_apply_drift_recovery_receipt",
        "recovery_id": recovery_id,
        "run_id": run_id_value,
        "source_policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_POLICY,
        "source_receipt_replay_result": replay.get("result"),
        "source_drift_verifier_result": verifier.get("result"),
        "result": result,
        "summary": summary,
        "drift_items": drift_items,
        "recovery_actions": recovery_actions,
        "dry_run_plan": dry_run_plan,
        "rollback_plan": rollback_plan,
        "checks": checks,
        "safety": safety,
    }
    artifact_bytes = _canonical_retry_exception_artifact_bytes(artifact_payload)
    artifact_relative_path = (
        f"artifacts/pchome_growth/retry_exception_closeout/"
        f"controlled_apply_drift_recovery/{recovery_id}.json"
    )
    recovery_artifact = {
        "key": "retry_exception_controlled_apply_drift_recovery_receipt",
        "artifact_type": "controlled_apply_drift_recovery_receipt",
        "relative_path": artifact_relative_path,
        "payload_sha256": hashlib.sha256(artifact_bytes).hexdigest(),
        "byte_count": len(artifact_bytes),
        "payload": artifact_payload,
        "materialized": False,
        "writes_database": False,
    }
    materialized_recovery_artifacts: list[dict[str, Any]] = []
    if materialize_artifacts and source_ready:
        target_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
        target_path.parent.mkdir(parents=True, exist_ok=True)
        target_path.write_bytes(artifact_bytes)
        materialized_recovery_artifacts.append({
            "key": recovery_artifact["key"],
            "relative_path": artifact_relative_path,
            "absolute_path": str(target_path),
            "payload_sha256": recovery_artifact["payload_sha256"],
            "written_byte_count": target_path.stat().st_size,
            "writes_database": False,
        })
        recovery_artifact["materialized"] = True
        recovery_artifact["absolute_path"] = str(target_path)
    artifact_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
    artifact_sha = hashlib.sha256(artifact_path.read_bytes()).hexdigest() if artifact_path.exists() else ""
    artifact_hash_match = bool(artifact_sha) and artifact_sha == recovery_artifact["payload_sha256"]
    summary["recovery_artifact_materialized_count"] = len(materialized_recovery_artifacts) or (1 if artifact_hash_match else 0)
    summary["recovery_artifact_hash_match_count"] = 1 if artifact_hash_match else 0
    safety["writes_artifact_count"] = len(materialized_recovery_artifacts)
    checks.extend([
        {
            "check": "recovery_artifact_materialized_when_requested",
            "passed": (not materialize_artifacts) or (source_ready and artifact_path.exists()),
        },
        {
            "check": "recovery_artifact_hash_matches_expected",
            "passed": (not materialize_artifacts) or artifact_hash_match,
        },
    ])
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_POLICY,
        "result": result,
        "success": result in {
            "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_PACKAGE_READY",
            "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_NOT_REQUIRED",
        },
        "summary": summary,
        "drift_recovery": {
            "recovery_id": recovery_id,
            "stage": "P2_retry_exception_controlled_apply_drift_recovery",
            "status": result,
            "source_receipt_replay_result": replay.get("result"),
            "source_drift_verifier_result": verifier.get("result"),
            "ready": result == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_PACKAGE_READY",
            "materialize_artifacts": bool(materialize_artifacts),
            "requires_production_version_truth": True,
        },
        "drift_items": drift_items,
        "recovery_actions": recovery_actions,
        "dry_run_plan": dry_run_plan,
        "rollback_plan": rollback_plan,
        "source_receipt_replay_summary": replay_summary,
        "source_drift_verifier_summary": verifier_summary,
        "recovery_artifact": recovery_artifact,
        "materialized_recovery_artifacts": materialized_recovery_artifacts,
        "post_recovery_artifact_verifier": {
            "expected_sha256": recovery_artifact["payload_sha256"],
            "actual_sha256": artifact_sha,
            "hash_match": artifact_hash_match,
            "writes_database": False,
        },
        "checks": checks,
        "check_count": len(checks),
        "all_checks_passed": all(check.get("passed") is True for check in checks),
        "next_actions": [
            "Run these actions through a controlled check-mode executor before any database apply.",
            "After re-apply, run receipt replay and drift verifier again; acceptance is zero drift.",
            "If no drift exists, keep this package as no-op evidence and continue compact readback work.",
        ],
        "safety": safety,
    }


def _compact_retry_exception_artifact_readback(
    root: Path,
    subdir: str,
    *,
    artifact_key: str,
    run_id: str | None = None,
) -> dict[str, Any]:
    path = _find_retry_exception_artifact_file(root, subdir, run_id)
    payload = _load_retry_exception_json_artifact(path)
    actual_sha = hashlib.sha256(path.read_bytes()).hexdigest() if path and path.exists() else ""
    return {
        "artifact_key": artifact_key,
        "exists": bool(path and path.exists()),
        "relative_path": str(path.relative_to(root)) if path and path.exists() else None,
        "absolute_path": str(path) if path and path.exists() else None,
        "payload_sha256": actual_sha,
        "byte_count": path.stat().st_size if path and path.exists() else 0,
        "result": payload.get("result"),
        "run_id": payload.get("run_id"),
        "summary": payload.get("summary") or {},
        "writes_database": False,
    }


def _compact_package_artifact_readback(package: dict[str, Any], artifact_key: str) -> dict[str, Any]:
    artifact = (
        package.get("executor_receipt_artifact")
        or package.get("drift_verifier_artifact")
        or package.get("recovery_artifact")
        or {}
    )
    verifier = (
        package.get("post_executor_receipt_verifier")
        or package.get("post_drift_verifier_artifact_verifier")
        or package.get("post_recovery_artifact_verifier")
        or {}
    )
    return {
        "artifact_key": artifact_key,
        "exists": bool(verifier.get("actual_sha256")),
        "relative_path": artifact.get("relative_path"),
        "payload_sha256": verifier.get("actual_sha256") or artifact.get("payload_sha256") or "",
        "expected_sha256": verifier.get("expected_sha256") or artifact.get("payload_sha256") or "",
        "hash_match": bool(verifier.get("hash_match")),
        "byte_count": artifact.get("byte_count") or 0,
        "result": package.get("result"),
        "summary": package.get("summary") or {},
        "writes_database": False,
    }


def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_compact_readback_package(
    *,
    artifact_root: str | Path | None = None,
    run_id: str | None = None,
    engine: Any = None,
    source_receipt_replay: dict[str, Any] | None = None,
    source_drift_verifier: dict[str, Any] | None = None,
    source_drift_recovery: dict[str, Any] | None = None,
    materialize_artifacts: bool = False,
) -> dict[str, Any]:
    """Build a compact product-facing readback for apply / replay / drift / recovery receipts."""
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    apply_receipt = _compact_retry_exception_artifact_readback(
        root,
        "controlled_apply_executor",
        artifact_key="retry_exception_controlled_apply_executor_receipt",
        run_id=run_id,
    )
    replay = source_receipt_replay or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
        artifact_root=root,
        run_id=run_id,
        materialize_artifacts=False,
        engine=engine,
    )
    drift = source_drift_verifier or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=replay,
        materialize_artifacts=False,
    )
    recovery = source_drift_recovery or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_recovery_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=replay,
        source_drift_verifier=drift,
        materialize_artifacts=False,
    )
    replay_summary = replay.get("summary") or {}
    drift_summary = drift.get("summary") or {}
    recovery_summary = recovery.get("summary") or {}
    selector_count = int(drift_summary.get("target_selector_count") or replay_summary.get("target_selector_count") or 0)
    readback_pass_count = int(
        drift_summary.get("post_apply_readback_pass_count")
        or replay_summary.get("post_apply_readback_pass_count")
        or 0
    )
    drift_count = int(drift_summary.get("drift_count") or 0)
    recovery_action_count = int(recovery_summary.get("drift_recovery_action_count") or 0)
    replay_hash_match_count = int(replay_summary.get("executor_receipt_hash_match_count") or 0)
    drift_hash_match_count = int(drift_summary.get("drift_verifier_artifact_hash_match_count") or 0)
    recovery_hash_match_count = int(recovery_summary.get("recovery_artifact_hash_match_count") or 0)
    if not apply_receipt.get("exists") and replay_hash_match_count:
        apply_receipt = _compact_package_artifact_readback(
            replay,
            "retry_exception_controlled_apply_executor_replay_receipt",
        )
        apply_receipt["fallback_from"] = "receipt_replay_apply_closeout"
    apply_hash_match_count = 1 if (
        bool(apply_receipt.get("hash_match"))
        or (apply_receipt.get("exists") and len(str(apply_receipt.get("payload_sha256") or "")) == 64)
    ) else 0

    if drift_count:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_DRIFT_REQUIRES_RECOVERY"
        next_machine_action = "run_controlled_reapply_check_mode"
        product_status = "blocked"
    elif (
        selector_count
        and readback_pass_count == selector_count
        and replay_hash_match_count
        and drift.get("result") == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIED"
        and recovery.get("result") == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_NOT_REQUIRED"
    ):
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_VERIFIED"
        next_machine_action = "keep_monitoring_drift"
        product_status = "completed"
    elif replay.get("missing_artifacts"):
        result = "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_ARTIFACTS"
        next_machine_action = "restore_or_materialize_source_receipts"
        product_status = "waiting"
    else:
        result = "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_BASELINE"
        next_machine_action = "run_receipt_replay_and_drift_verifier"
        product_status = "waiting"

    summary = {
        "target_selector_count": selector_count,
        "post_apply_readback_pass_count": readback_pass_count,
        "post_apply_readback_fail_count": max(selector_count - readback_pass_count, 0),
        "drift_count": drift_count,
        "drift_recovery_action_count": recovery_action_count,
        "drift_reapply_ready_count": int(recovery_summary.get("drift_reapply_ready_count") or 0),
        "apply_receipt_hash_match_count": apply_hash_match_count,
        "replay_receipt_hash_match_count": replay_hash_match_count,
        "drift_verifier_artifact_hash_match_count": drift_hash_match_count,
        "recovery_artifact_hash_match_count": recovery_hash_match_count,
        "compact_readback_artifact_materialized_count": 0,
        "compact_readback_artifact_hash_match_count": 0,
        "writes_database_count": 0,
    }
    receipts = {
        "apply": apply_receipt,
        "replay": _compact_package_artifact_readback(
            replay,
            "retry_exception_controlled_apply_executor_replay_receipt",
        ),
        "drift": _compact_package_artifact_readback(
            drift,
            "retry_exception_controlled_apply_drift_verifier_receipt",
        ),
        "recovery": _compact_package_artifact_readback(
            recovery,
            "retry_exception_controlled_apply_drift_recovery_receipt",
        ),
    }
    safety = {
        "ai_controlled_apply": True,
        "compact_readback": True,
        "reads_artifact_files": True,
        "reads_database": engine is not None,
        "writes_database": False,
        "writes_database_count": 0,
        "writes_artifact_count": 0,
        "syncs_external_offers": False,
        "dispatches_telegram": False,
        "gemini_allowed": False,
        "requires_production_version_truth": True,
    }
    compact_id_payload = {
        "run_id": run_id or (replay.get("receipt_replay") or {}).get("run_id") or "",
        "result": result,
        "summary": summary,
        "receipts": receipts,
    }
    compact_id = (
        "pchome-retry-exception-controlled-apply-compact-readback-"
        + hashlib.sha256(
            json.dumps(compact_id_payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
        ).hexdigest()[:16]
    )
    checks = [
        {
            "check": "apply_receipt_loaded_if_available",
            "passed": bool(apply_receipt.get("exists")) or replay_hash_match_count > 0,
        },
        {"check": "receipt_replay_loaded", "passed": bool(replay)},
        {"check": "drift_verifier_loaded", "passed": bool(drift)},
        {"check": "drift_recovery_loaded", "passed": bool(recovery)},
        {"check": "post_apply_readback_matches_selector_count", "passed": (not selector_count) or readback_pass_count == selector_count},
        {"check": "compact_readback_does_not_write_database", "passed": True},
    ]
    artifact_payload = {
        "artifact_key": "retry_exception_controlled_apply_compact_readback_receipt",
        "compact_readback_id": compact_id,
        "source_policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_POLICY,
        "result": result,
        "product_status": product_status,
        "next_machine_action": next_machine_action,
        "summary": summary,
        "receipts": receipts,
        "checks": checks,
        "safety": safety,
    }
    artifact_bytes = _canonical_retry_exception_artifact_bytes(artifact_payload)
    artifact_relative_path = (
        f"artifacts/pchome_growth/retry_exception_closeout/"
        f"controlled_apply_compact_readback/{compact_id}.json"
    )
    compact_artifact = {
        "key": "retry_exception_controlled_apply_compact_readback_receipt",
        "artifact_type": "controlled_apply_compact_readback_receipt",
        "relative_path": artifact_relative_path,
        "payload_sha256": hashlib.sha256(artifact_bytes).hexdigest(),
        "byte_count": len(artifact_bytes),
        "payload": artifact_payload,
        "materialized": False,
        "writes_database": False,
    }
    materialized_compact_artifacts: list[dict[str, Any]] = []
    if materialize_artifacts and selector_count:
        target_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
        target_path.parent.mkdir(parents=True, exist_ok=True)
        target_path.write_bytes(artifact_bytes)
        materialized_compact_artifacts.append({
            "key": compact_artifact["key"],
            "relative_path": artifact_relative_path,
            "absolute_path": str(target_path),
            "payload_sha256": compact_artifact["payload_sha256"],
            "written_byte_count": target_path.stat().st_size,
            "writes_database": False,
        })
        compact_artifact["materialized"] = True
        compact_artifact["absolute_path"] = str(target_path)
    artifact_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
    artifact_sha = hashlib.sha256(artifact_path.read_bytes()).hexdigest() if artifact_path.exists() else ""
    artifact_hash_match = bool(artifact_sha) and artifact_sha == compact_artifact["payload_sha256"]
    summary["compact_readback_artifact_materialized_count"] = len(materialized_compact_artifacts) or (1 if artifact_hash_match else 0)
    summary["compact_readback_artifact_hash_match_count"] = 1 if artifact_hash_match else 0
    safety["writes_artifact_count"] = len(materialized_compact_artifacts)
    checks.extend([
        {
            "check": "compact_artifact_materialized_when_requested",
            "passed": (not materialize_artifacts) or (selector_count > 0 and artifact_path.exists()),
        },
        {
            "check": "compact_artifact_hash_matches_expected",
            "passed": (not materialize_artifacts) or artifact_hash_match,
        },
    ])
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_POLICY,
        "result": result,
        "success": result in {
            "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_VERIFIED",
            "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_DRIFT_REQUIRES_RECOVERY",
        },
        "summary": summary,
        "compact_readback": {
            "compact_readback_id": compact_id,
            "stage": "P2_retry_exception_controlled_apply_compact_readback",
            "status": product_status,
            "next_machine_action": next_machine_action,
            "materialize_artifacts": bool(materialize_artifacts),
            "requires_production_version_truth": True,
        },
        "receipts": receipts,
        "compact_artifact": compact_artifact,
        "materialized_compact_artifacts": materialized_compact_artifacts,
        "post_compact_artifact_verifier": {
            "expected_sha256": compact_artifact["payload_sha256"],
            "actual_sha256": artifact_sha,
            "hash_match": artifact_hash_match,
            "writes_database": False,
        },
        "checks": checks,
        "check_count": len(checks),
        "all_checks_passed": all(check.get("passed") is True for check in checks),
        "next_actions": [
            "Use this compact readback as the product/UI source for controlled apply status.",
            "If drift_count is zero, continue automated drift monitoring.",
            "If drift_count is positive, execute the recovery package through controlled check-mode first.",
        ],
        "safety": safety,
    }


_CONTROLLED_APPLY_RETENTION_FAMILIES = [
    {
        "family": "verifier_inputs",
        "artifact_key": "retry_exception_closeout_verifier_input_artifact",
        "subdir": "verifier_inputs",
    },
    {
        "family": "identity_readback",
        "artifact_key": "retry_exception_closeout_identity_readback_artifact",
        "subdir": "identity_readback",
    },
    {
        "family": "controlled_apply_preflight",
        "artifact_key": "retry_exception_controlled_apply_preflight_artifact",
        "subdir": "controlled_apply_preflight",
    },
    {
        "family": "controlled_apply_executor",
        "artifact_key": "retry_exception_controlled_apply_executor_receipt",
        "subdir": "controlled_apply_executor",
    },
    {
        "family": "controlled_apply_executor_replay",
        "artifact_key": "retry_exception_controlled_apply_executor_replay_receipt",
        "subdir": "controlled_apply_executor_replay",
    },
    {
        "family": "controlled_apply_drift_verifier",
        "artifact_key": "retry_exception_controlled_apply_drift_verifier_receipt",
        "subdir": "controlled_apply_drift_verifier",
    },
    {
        "family": "controlled_apply_drift_recovery",
        "artifact_key": "retry_exception_controlled_apply_drift_recovery_receipt",
        "subdir": "controlled_apply_drift_recovery",
    },
    {
        "family": "controlled_apply_compact_readback",
        "artifact_key": "retry_exception_controlled_apply_compact_readback_receipt",
        "subdir": "controlled_apply_compact_readback",
    },
]


def _retry_exception_artifact_retention_id(summary: dict[str, Any], protected_paths: list[str]) -> str:
    payload = {"summary": summary, "protected_paths": protected_paths}
    digest = hashlib.sha256(
        json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()[:16]
    return f"pchome-retry-exception-controlled-apply-artifact-retention-{digest}"


def _scan_retry_exception_retention_family(
    root: Path,
    family: dict[str, str],
    *,
    keep_latest_per_family: int,
    protected_relative_paths: set[str],
) -> dict[str, Any]:
    artifact_dir = root / "artifacts" / "pchome_growth" / "retry_exception_closeout" / family["subdir"]
    paths = sorted(
        artifact_dir.glob("*.json") if artifact_dir.exists() else [],
        key=lambda path: path.stat().st_mtime,
        reverse=True,
    )
    artifacts: list[dict[str, Any]] = []
    keep_count = 0
    prune_candidate_count = 0
    total_bytes = 0
    prune_candidate_bytes = 0
    for index, path in enumerate(paths, start=1):
        relative_path = str(path.relative_to(root))
        byte_count = path.stat().st_size
        total_bytes += byte_count
        protected = index <= keep_latest_per_family or relative_path in protected_relative_paths
        sha = hashlib.sha256(path.read_bytes()).hexdigest()
        decision = "keep" if protected else "candidate_for_retention_prune"
        if protected:
            keep_count += 1
        else:
            prune_candidate_count += 1
            prune_candidate_bytes += byte_count
        artifacts.append({
            "family": family["family"],
            "artifact_key": family["artifact_key"],
            "relative_path": relative_path,
            "payload_sha256": sha,
            "byte_count": byte_count,
            "latest_rank": index,
            "protected_by_latest_window": index <= keep_latest_per_family,
            "protected_by_active_chain": relative_path in protected_relative_paths,
            "retention_decision": decision,
            "delete_in_package": False,
            "writes_database": False,
        })
    return {
        "family": family["family"],
        "artifact_key": family["artifact_key"],
        "subdir": family["subdir"],
        "artifact_count": len(artifacts),
        "keep_count": keep_count,
        "prune_candidate_count": prune_candidate_count,
        "total_byte_count": total_bytes,
        "prune_candidate_byte_count": prune_candidate_bytes,
        "artifacts": artifacts,
    }


def _compact_readback_protected_relative_paths(compact_readback: dict[str, Any]) -> set[str]:
    protected_paths: set[str] = set()
    for receipt in (compact_readback.get("receipts") or {}).values():
        relative_path = receipt.get("relative_path")
        if relative_path:
            protected_paths.add(str(relative_path))
    compact_artifact = compact_readback.get("compact_artifact") or {}
    if compact_artifact.get("relative_path"):
        protected_paths.add(str(compact_artifact["relative_path"]))
    return protected_paths


def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_artifact_retention_package(
    *,
    artifact_root: str | Path | None = None,
    run_id: str | None = None,
    engine: Any = None,
    source_compact_readback: dict[str, Any] | None = None,
    keep_latest_per_family: int = 3,
    materialize_artifacts: bool = False,
) -> dict[str, Any]:
    """Build a no-delete retention policy package for controlled-apply artifacts."""
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    keep_latest = max(1, int(keep_latest_per_family or 3))
    compact_readback = source_compact_readback or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_compact_readback_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        materialize_artifacts=False,
    )
    protected_paths = _compact_readback_protected_relative_paths(compact_readback)
    family_reports = [
        _scan_retry_exception_retention_family(
            root,
            family,
            keep_latest_per_family=keep_latest,
            protected_relative_paths=protected_paths,
        )
        for family in _CONTROLLED_APPLY_RETENTION_FAMILIES
    ]
    artifact_count = sum(int(report.get("artifact_count") or 0) for report in family_reports)
    keep_count = sum(int(report.get("keep_count") or 0) for report in family_reports)
    prune_candidate_count = sum(int(report.get("prune_candidate_count") or 0) for report in family_reports)
    total_bytes = sum(int(report.get("total_byte_count") or 0) for report in family_reports)
    prune_candidate_bytes = sum(int(report.get("prune_candidate_byte_count") or 0) for report in family_reports)
    protected_path_list = sorted(protected_paths)
    summary = {
        "retention_family_count": len(family_reports),
        "artifact_count": artifact_count,
        "retained_artifact_count": keep_count,
        "prune_candidate_count": prune_candidate_count,
        "total_byte_count": total_bytes,
        "prune_candidate_byte_count": prune_candidate_bytes,
        "keep_latest_per_family": keep_latest,
        "protected_active_chain_count": len(protected_path_list),
        "retention_prune_executes_count": 0,
        "retention_artifact_materialized_count": 0,
        "retention_artifact_hash_match_count": 0,
        "writes_database_count": 0,
    }
    result = (
        "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ARTIFACT_RETENTION_POLICY_READY"
        if artifact_count
        else "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_ARTIFACT_RETENTION_INPUTS"
    )
    retention_id = _retry_exception_artifact_retention_id(summary, protected_path_list)
    safety = {
        "ai_controlled_apply": True,
        "artifact_retention": True,
        "reads_artifact_files": True,
        "reads_database": engine is not None,
        "deletes_artifacts": False,
        "retention_prune_executes": False,
        "writes_database": False,
        "writes_database_count": 0,
        "writes_artifact_count": 0,
        "syncs_external_offers": False,
        "dispatches_telegram": False,
        "gemini_allowed": False,
        "requires_production_version_truth": True,
    }
    checks = [
        {"check": "compact_readback_loaded", "passed": bool(compact_readback)},
        {"check": "retention_families_scanned", "passed": len(family_reports) == len(_CONTROLLED_APPLY_RETENTION_FAMILIES)},
        {"check": "active_chain_paths_protected", "passed": bool(protected_path_list)},
        {"check": "retention_policy_does_not_delete_artifacts", "passed": True},
        {"check": "retention_policy_does_not_write_database", "passed": True},
    ]
    artifact_payload = {
        "artifact_key": "retry_exception_controlled_apply_artifact_retention_policy_receipt",
        "retention_id": retention_id,
        "source_policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_ARTIFACT_RETENTION_POLICY,
        "source_compact_readback_result": compact_readback.get("result"),
        "result": result,
        "summary": summary,
        "protected_active_chain_paths": protected_path_list,
        "family_reports": family_reports,
        "checks": checks,
        "safety": safety,
    }
    artifact_bytes = _canonical_retry_exception_artifact_bytes(artifact_payload)
    artifact_relative_path = (
        f"artifacts/pchome_growth/retry_exception_closeout/"
        f"controlled_apply_artifact_retention/{retention_id}.json"
    )
    retention_artifact = {
        "key": "retry_exception_controlled_apply_artifact_retention_policy_receipt",
        "artifact_type": "controlled_apply_artifact_retention_policy_receipt",
        "relative_path": artifact_relative_path,
        "payload_sha256": hashlib.sha256(artifact_bytes).hexdigest(),
        "byte_count": len(artifact_bytes),
        "payload": artifact_payload,
        "materialized": False,
        "writes_database": False,
    }
    materialized_retention_artifacts: list[dict[str, Any]] = []
    if materialize_artifacts and artifact_count:
        target_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
        target_path.parent.mkdir(parents=True, exist_ok=True)
        target_path.write_bytes(artifact_bytes)
        materialized_retention_artifacts.append({
            "key": retention_artifact["key"],
            "relative_path": artifact_relative_path,
            "absolute_path": str(target_path),
            "payload_sha256": retention_artifact["payload_sha256"],
            "written_byte_count": target_path.stat().st_size,
            "writes_database": False,
        })
        retention_artifact["materialized"] = True
        retention_artifact["absolute_path"] = str(target_path)
    artifact_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
    artifact_sha = hashlib.sha256(artifact_path.read_bytes()).hexdigest() if artifact_path.exists() else ""
    artifact_hash_match = bool(artifact_sha) and artifact_sha == retention_artifact["payload_sha256"]
    summary["retention_artifact_materialized_count"] = len(materialized_retention_artifacts) or (1 if artifact_hash_match else 0)
    summary["retention_artifact_hash_match_count"] = 1 if artifact_hash_match else 0
    safety["writes_artifact_count"] = len(materialized_retention_artifacts)
    checks.extend([
        {
            "check": "retention_artifact_materialized_when_requested",
            "passed": (not materialize_artifacts) or (artifact_count > 0 and artifact_path.exists()),
        },
        {
            "check": "retention_artifact_hash_matches_expected",
            "passed": (not materialize_artifacts) or artifact_hash_match,
        },
    ])
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_ARTIFACT_RETENTION_POLICY,
        "result": result,
        "success": artifact_count > 0,
        "summary": summary,
        "artifact_retention": {
            "retention_id": retention_id,
            "stage": "P2_retry_exception_controlled_apply_artifact_retention",
            "status": "ready" if artifact_count else "waiting",
            "keep_latest_per_family": keep_latest,
            "protected_active_chain_count": len(protected_path_list),
            "materialize_artifacts": bool(materialize_artifacts),
            "requires_production_version_truth": True,
        },
        "protected_active_chain_paths": protected_path_list,
        "family_reports": family_reports,
        "retention_artifact": retention_artifact,
        "materialized_retention_artifacts": materialized_retention_artifacts,
        "post_retention_artifact_verifier": {
            "expected_sha256": retention_artifact["payload_sha256"],
            "actual_sha256": artifact_sha,
            "hash_match": artifact_hash_match,
            "writes_database": False,
        },
        "checks": checks,
        "check_count": len(checks),
        "all_checks_passed": all(check.get("passed") is True for check in checks),
        "next_actions": [
            "Use prune candidates only after a separate controlled delete executor is added.",
            "Keep the latest active compact readback chain protected before any artifact pruning.",
            "Expose retained/prune candidate counts on the product dashboard before enabling prune execution.",
        ],
        "safety": safety,
    }


def _retry_exception_controlled_apply_rollback_evidence_id(
    summary: dict[str, Any],
    rollback_actions: list[dict[str, Any]],
) -> str:
    payload = {"summary": summary, "rollback_actions": rollback_actions}
    digest = hashlib.sha256(
        json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")
    ).hexdigest()[:16]
    return f"pchome-retry-exception-controlled-apply-rollback-evidence-{digest}"


def build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_rollback_evidence_package(
    *,
    artifact_root: str | Path | None = None,
    run_id: str | None = None,
    engine: Any = None,
    source_receipt_replay: dict[str, Any] | None = None,
    source_drift_verifier: dict[str, Any] | None = None,
    source_drift_recovery: dict[str, Any] | None = None,
    source_compact_readback: dict[str, Any] | None = None,
    source_artifact_retention: dict[str, Any] | None = None,
    materialize_artifacts: bool = False,
) -> dict[str, Any]:
    """Aggregate rollback evidence for the controlled-apply family without executing rollback."""
    root = Path(artifact_root) if artifact_root is not None else Path.cwd() / "data"
    replay = source_receipt_replay or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
        artifact_root=root,
        run_id=run_id,
        materialize_artifacts=False,
        engine=engine,
    )
    drift = source_drift_verifier or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=replay,
        materialize_artifacts=False,
    )
    recovery = source_drift_recovery or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_recovery_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=replay,
        source_drift_verifier=drift,
        materialize_artifacts=False,
    )
    compact = source_compact_readback or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_compact_readback_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=replay,
        source_drift_verifier=drift,
        source_drift_recovery=recovery,
        materialize_artifacts=False,
    )
    retention = source_artifact_retention or build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_artifact_retention_package(
        artifact_root=root,
        run_id=run_id,
        engine=engine,
        source_compact_readback=compact,
        materialize_artifacts=False,
    )

    replay_summary = replay.get("summary") or {}
    drift_summary = drift.get("summary") or {}
    recovery_summary = recovery.get("summary") or {}
    compact_summary = compact.get("summary") or {}
    retention_summary = retention.get("summary") or {}
    drift_count = int(drift_summary.get("drift_count") or recovery_summary.get("drift_count") or compact_summary.get("drift_count") or 0)
    recovery_actions = list(recovery.get("recovery_actions") or [])
    ready_actions = [
        item for item in recovery_actions
        if item.get("status") == "ready_for_controlled_reapply"
    ]
    rollback_actions = []
    for action in recovery_actions:
        rollback_actions.append({
            "action_id": action.get("action_id"),
            "selector_id": action.get("selector_id"),
            "momo_icode": action.get("momo_icode"),
            "expected_pchome_id": action.get("expected_pchome_id"),
            "actual_pchome_id": action.get("actual_pchome_id"),
            "status": action.get("status"),
            "rollback_sql_shape": action.get("rollback_sql_shape"),
            "controlled_reapply_sql_shape": action.get("controlled_reapply_sql_shape"),
            "selector_bindings": action.get("selector_bindings") or {},
            "acceptance_gates": list(action.get("acceptance_gates") or []),
            "executes_in_package": False,
            "writes_database": False,
        })

    rollback_required = drift_count > 0
    rollback_ready = rollback_required and bool(ready_actions) and len(ready_actions) == drift_count
    no_rollback_required = (
        not rollback_required
        and (
            drift.get("result") == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIED"
            or recovery.get("result") == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_NOT_REQUIRED"
            or compact.get("result") == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_VERIFIED"
        )
    )
    missing_artifacts = list(replay.get("missing_artifacts") or [])
    retention_ready = bool(retention_summary.get("artifact_count") or retention.get("success"))
    family_evidence = [
        {
            "family": "controlled_apply_receipt_replay",
            "result": replay.get("result"),
            "selector_count": int(replay_summary.get("target_selector_count") or 0),
            "readback_pass_count": int(replay_summary.get("post_apply_readback_pass_count") or 0),
            "hash_match_count": int(replay_summary.get("executor_receipt_hash_match_count") or 0),
            "rollback_role": "baseline_expected_state",
            "writes_database": False,
        },
        {
            "family": "controlled_apply_drift_verifier",
            "result": drift.get("result"),
            "drift_count": drift_count,
            "hash_match_count": int(drift_summary.get("drift_verifier_artifact_hash_match_count") or 0),
            "rollback_role": "current_state_delta_detector",
            "writes_database": False,
        },
        {
            "family": "controlled_apply_drift_recovery",
            "result": recovery.get("result"),
            "action_count": len(recovery_actions),
            "ready_action_count": len(ready_actions),
            "hash_match_count": int(recovery_summary.get("recovery_artifact_hash_match_count") or 0),
            "rollback_role": "rollback_and_reapply_action_source",
            "writes_database": False,
        },
        {
            "family": "controlled_apply_compact_readback",
            "result": compact.get("result"),
            "product_status": (compact.get("compact_readback") or {}).get("status"),
            "next_machine_action": (compact.get("compact_readback") or {}).get("next_machine_action"),
            "hash_match_count": int(compact_summary.get("compact_readback_artifact_hash_match_count") or 0),
            "rollback_role": "product_facing_status_source",
            "writes_database": False,
        },
        {
            "family": "controlled_apply_artifact_retention",
            "result": retention.get("result"),
            "artifact_count": int(retention_summary.get("artifact_count") or 0),
            "protected_active_chain_count": int(retention_summary.get("protected_active_chain_count") or 0),
            "hash_match_count": int(retention_summary.get("retention_artifact_hash_match_count") or 0),
            "rollback_role": "evidence_chain_protection_source",
            "writes_database": False,
        },
    ]

    if rollback_ready:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_READY"
        product_status = "rollback_ready"
        next_machine_action = "run_controlled_reapply_check_mode"
    elif rollback_required:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_BLOCKED"
        product_status = "rollback_blocked"
        next_machine_action = "rebuild_selector_identity_before_rollback"
    elif no_rollback_required:
        result = "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_NOT_REQUIRED"
        product_status = "rollback_not_required"
        next_machine_action = "keep_monitoring_drift"
    elif missing_artifacts:
        result = "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_ARTIFACTS"
        product_status = "waiting"
        next_machine_action = "restore_or_materialize_source_receipts"
    else:
        result = "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_BASELINE"
        product_status = "waiting"
        next_machine_action = "run_receipt_replay_and_drift_verifier"

    summary = {
        "controlled_apply_family_count": len(family_evidence),
        "target_selector_count": int(replay_summary.get("target_selector_count") or compact_summary.get("target_selector_count") or 0),
        "post_apply_readback_pass_count": int(replay_summary.get("post_apply_readback_pass_count") or compact_summary.get("post_apply_readback_pass_count") or 0),
        "drift_count": drift_count,
        "rollback_required_count": 1 if rollback_required else 0,
        "rollback_action_count": len(rollback_actions),
        "rollback_ready_action_count": len(ready_actions),
        "rollback_blocked_action_count": len(rollback_actions) - len(ready_actions),
        "retention_artifact_count": int(retention_summary.get("artifact_count") or 0),
        "protected_active_chain_count": int(retention_summary.get("protected_active_chain_count") or 0),
        "rollback_evidence_ready_count": 1 if (rollback_ready or no_rollback_required) else 0,
        "rollback_evidence_artifact_materialized_count": 0,
        "rollback_evidence_artifact_hash_match_count": 0,
        "primary_human_gate_count": 0,
        "writes_database_count": 0,
    }
    rollback_evidence_id = _retry_exception_controlled_apply_rollback_evidence_id(summary, rollback_actions)
    safety = {
        "ai_controlled_apply": True,
        "rollback_evidence": True,
        "reads_artifact_files": True,
        "reads_database": engine is not None,
        "executes_rollback": False,
        "executes_reapply": False,
        "executes_sql": False,
        "deletes_artifacts": False,
        "writes_database": False,
        "writes_database_count": 0,
        "writes_artifact_count": 0,
        "syncs_external_offers": False,
        "dispatches_telegram": False,
        "gemini_allowed": False,
        "requires_production_version_truth": True,
    }
    checks = [
        {"check": "receipt_replay_loaded", "passed": bool(replay)},
        {"check": "drift_verifier_loaded", "passed": bool(drift)},
        {"check": "drift_recovery_loaded", "passed": bool(recovery)},
        {"check": "compact_readback_loaded", "passed": bool(compact)},
        {"check": "artifact_retention_loaded", "passed": bool(retention)},
        {"check": "rollback_actions_cover_detected_drift", "passed": (not rollback_required) or len(ready_actions) == drift_count},
        {"check": "artifact_retention_protects_evidence_chain", "passed": retention_ready or not rollback_required},
        {"check": "rollback_evidence_has_no_primary_human_gate", "passed": True},
        {"check": "rollback_evidence_does_not_execute_sql", "passed": True},
        {"check": "rollback_evidence_does_not_write_database", "passed": True},
    ]
    artifact_payload = {
        "artifact_key": "retry_exception_controlled_apply_rollback_evidence_receipt",
        "rollback_evidence_id": rollback_evidence_id,
        "source_policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_POLICY,
        "source_compact_readback_result": compact.get("result"),
        "source_drift_recovery_result": recovery.get("result"),
        "source_artifact_retention_result": retention.get("result"),
        "result": result,
        "product_status": product_status,
        "next_machine_action": next_machine_action,
        "summary": summary,
        "family_evidence": family_evidence,
        "rollback_actions": rollback_actions,
        "checks": checks,
        "safety": safety,
    }
    artifact_bytes = _canonical_retry_exception_artifact_bytes(artifact_payload)
    artifact_relative_path = (
        f"artifacts/pchome_growth/retry_exception_closeout/"
        f"controlled_apply_rollback_evidence/{rollback_evidence_id}.json"
    )
    rollback_evidence_artifact = {
        "key": "retry_exception_controlled_apply_rollback_evidence_receipt",
        "artifact_type": "controlled_apply_rollback_evidence_receipt",
        "relative_path": artifact_relative_path,
        "payload_sha256": hashlib.sha256(artifact_bytes).hexdigest(),
        "byte_count": len(artifact_bytes),
        "payload": artifact_payload,
        "materialized": False,
        "writes_database": False,
    }
    materialized_rollback_evidence_artifacts: list[dict[str, Any]] = []
    if materialize_artifacts and (rollback_ready or no_rollback_required):
        target_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
        target_path.parent.mkdir(parents=True, exist_ok=True)
        target_path.write_bytes(artifact_bytes)
        materialized_rollback_evidence_artifacts.append({
            "key": rollback_evidence_artifact["key"],
            "relative_path": artifact_relative_path,
            "absolute_path": str(target_path),
            "payload_sha256": rollback_evidence_artifact["payload_sha256"],
            "written_byte_count": target_path.stat().st_size,
            "writes_database": False,
        })
        rollback_evidence_artifact["materialized"] = True
        rollback_evidence_artifact["absolute_path"] = str(target_path)
    artifact_path = _resolve_retry_exception_artifact_path(root, artifact_relative_path)
    artifact_sha = hashlib.sha256(artifact_path.read_bytes()).hexdigest() if artifact_path.exists() else ""
    artifact_hash_match = bool(artifact_sha) and artifact_sha == rollback_evidence_artifact["payload_sha256"]
    summary["rollback_evidence_artifact_materialized_count"] = (
        len(materialized_rollback_evidence_artifacts) or (1 if artifact_hash_match else 0)
    )
    summary["rollback_evidence_artifact_hash_match_count"] = 1 if artifact_hash_match else 0
    safety["writes_artifact_count"] = len(materialized_rollback_evidence_artifacts)
    checks.extend([
        {
            "check": "rollback_evidence_artifact_materialized_when_requested",
            "passed": (not materialize_artifacts) or ((rollback_ready or no_rollback_required) and artifact_path.exists()),
        },
        {
            "check": "rollback_evidence_artifact_hash_matches_expected",
            "passed": (not materialize_artifacts) or artifact_hash_match,
        },
    ])
    return {
        "policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_POLICY,
        "result": result,
        "success": result in {
            "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_READY",
            "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ROLLBACK_EVIDENCE_NOT_REQUIRED",
        },
        "summary": summary,
        "rollback_evidence": {
            "rollback_evidence_id": rollback_evidence_id,
            "stage": "P3_retry_exception_controlled_apply_rollback_evidence",
            "status": product_status,
            "rollback_required": rollback_required,
            "next_machine_action": next_machine_action,
            "materialize_artifacts": bool(materialize_artifacts),
            "requires_production_version_truth": True,
        },
        "family_evidence": family_evidence,
        "rollback_actions": rollback_actions,
        "rollback_evidence_artifact": rollback_evidence_artifact,
        "materialized_rollback_evidence_artifacts": materialized_rollback_evidence_artifacts,
        "post_rollback_evidence_artifact_verifier": {
            "expected_sha256": rollback_evidence_artifact["payload_sha256"],
            "actual_sha256": artifact_sha,
            "hash_match": artifact_hash_match,
            "writes_database": False,
        },
        "source_results": {
            "receipt_replay": replay.get("result"),
            "drift_verifier": drift.get("result"),
            "drift_recovery": recovery.get("result"),
            "compact_readback": compact.get("result"),
            "artifact_retention": retention.get("result"),
        },
        "checks": checks,
        "check_count": len(checks),
        "all_checks_passed": all(check.get("passed") is True for check in checks),
        "next_actions": [
            "If rollback_required is false, keep monitoring drift using the scheduled health summary.",
            "If rollback evidence is ready, run the controlled re-apply path in check-mode before any write.",
            "After any controlled re-apply, replay receipts and regenerate this rollback evidence package.",
        ],
        "safety": safety,
    }


def build_pchome_evidence_fetch_gate(
    payload: dict[str, Any],
    batch_size: int = 3,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    max_html_bytes: int = PCHOME_FETCH_MAX_HTML_BYTES,
    http_get: Any = None,
) -> dict[str, Any]:
    """Plan or execute a small read-only product-page evidence fetch gate."""
    batch_size = max(1, min(int(batch_size or 3), PCHOME_FETCH_MAX_BATCH_SIZE))
    timeout_seconds = max(1, min(int(timeout_seconds or PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS), 10))
    max_html_bytes = max(16_384, min(int(max_html_bytes or PCHOME_FETCH_MAX_HTML_BYTES), PCHOME_FETCH_MAX_HTML_BYTES))
    source_preview = build_pchome_evidence_source_preview(payload, batch_size=batch_size)
    candidates = list(source_preview.get("fetch_gate_candidates") or [])[:batch_size]
    receipts = []

    for candidate in candidates:
        product_url = candidate.get("product_url")
        allowed = _is_allowed_pchome_product_url(product_url)
        receipt = {
            "pchome_product_id": candidate.get("pchome_product_id") or "",
            "product_name": candidate.get("product_name") or "",
            "product_url": product_url,
            "fields": list(candidate.get("fields") or []),
            "allowed_domain": PCHOME_FETCH_ALLOWED_DOMAIN,
            "allowlist_passed": allowed,
            "execute_fetch_requested": bool(execute_fetch),
            "executed_fetch": False,
            "writes_database": False,
            "dispatches_telegram": False,
            "llm_calls": False,
            "parser_policy": PRODUCT_PAGE_EVIDENCE_PARSER_POLICY,
            "status": "PLANNED",
        }

        if not allowed:
            receipt["status"] = "BLOCKED_BY_ALLOWLIST"
            receipt["error"] = "product_url must be a PChome 24h /prod/ URL"
            receipts.append(receipt)
            continue
        if not execute_fetch:
            receipts.append(receipt)
            continue

        try:
            html, fetch_meta = _fetch_product_page_html(
                product_url,
                timeout_seconds=timeout_seconds,
                max_html_bytes=max_html_bytes,
                http_get=http_get,
            )
            parsed = parse_pchome_product_page_evidence_html(html, product_url=product_url)
            receipt.update(
                {
                    "status": "FETCHED_WITH_EVIDENCE"
                    if parsed.get("image_url") or parsed.get("availability")
                    else "FETCHED_NO_STRUCTURED_EVIDENCE",
                    "executed_fetch": True,
                    "fetch_meta": fetch_meta,
                    "parsed_evidence": {
                        "image_url": parsed.get("image_url"),
                        "availability": parsed.get("availability"),
                        "availability_raw": parsed.get("availability_raw"),
                        "jsonld_product_found": parsed.get("jsonld_product_found"),
                        "jsonld_offer_found": parsed.get("jsonld_offer_found"),
                        "fallbacks_used": parsed.get("fallbacks_used") or [],
                        "parser_warnings": parsed.get("parser_warnings") or [],
                    },
                }
            )
        except (requests.RequestException, ValueError, UnicodeError) as exc:
            receipt["status"] = "FETCH_FAILED"
            receipt["error"] = str(exc)
        receipts.append(receipt)

    executed_count = sum(1 for receipt in receipts if receipt.get("executed_fetch"))
    blocked_count = sum(1 for receipt in receipts if receipt.get("status") == "BLOCKED_BY_ALLOWLIST")
    failed_count = sum(1 for receipt in receipts if receipt.get("status") == "FETCH_FAILED")
    parsed_image_count = sum(1 for receipt in receipts if (receipt.get("parsed_evidence") or {}).get("image_url"))
    parsed_availability_count = sum(1 for receipt in receipts if (receipt.get("parsed_evidence") or {}).get("availability"))

    if not candidates:
        result = "NO_FETCH_CANDIDATES"
    elif not execute_fetch:
        result = "FETCH_GATE_PLANNED"
    elif parsed_image_count or parsed_availability_count:
        result = "FETCH_GATE_EXECUTED_WITH_EVIDENCE"
    elif failed_count or blocked_count:
        result = "FETCH_GATE_EXECUTED_WITH_BLOCKERS"
    else:
        result = "FETCH_GATE_EXECUTED_NO_EVIDENCE"

    return {
        "policy": EVIDENCE_FETCH_GATE_POLICY,
        "result": result,
        "success": bool(source_preview.get("success")),
        "generated_at": source_preview.get("generated_at"),
        "source_policy": source_preview.get("policy"),
        "stats": source_preview.get("stats") or {},
        "summary": {
            "candidate_count": len(candidates),
            "receipt_count": len(receipts),
            "executed_fetch_count": executed_count,
            "blocked_count": blocked_count,
            "failed_count": failed_count,
            "parsed_image_count": parsed_image_count,
            "parsed_availability_count": parsed_availability_count,
            "max_batch_size": PCHOME_FETCH_MAX_BATCH_SIZE,
        },
        "fetch_config": {
            "execute_fetch": bool(execute_fetch),
            "allowed_domain": PCHOME_FETCH_ALLOWED_DOMAIN,
            "timeout_seconds": timeout_seconds,
            "max_html_bytes": max_html_bytes,
            "method": "GET",
        },
        "fetch_receipts": receipts,
        "source_preview_summary": source_preview.get("summary") or {},
        "safety": {
            "read_only_fetch_gate": True,
            "writes_database": False,
            "executes_search": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "requires_production_version_truth": True,
            "requires_domain_allowlist": True,
            "requires_html_size_cap": True,
            "requires_operator_review_before_write": True,
        },
        "next_actions": [
            "Review fetch receipts for image_url and availability before any write-gated mapping action.",
            "Keep parsed evidence as preview evidence until an explicit evidence write path exists.",
            "Investigate price payload gaps separately from product-page image and availability evidence.",
        ],
    }


def _merge_task_with_fetch_receipt(task: dict[str, Any], receipt: dict[str, Any] | None) -> dict[str, Any]:
    present_fields = set(task.get("present_fields") or [])
    missing_fields = set(task.get("missing_fields") or [])
    blocking_missing_fields = set(task.get("blocking_missing_fields") or [])
    parsed = (receipt or {}).get("parsed_evidence") or {}
    evidence_delta = {}

    if parsed.get("image_url"):
        present_fields.add("image")
        missing_fields.discard("image")
        blocking_missing_fields.discard("image")
        evidence_delta["image_url"] = parsed.get("image_url")
    if parsed.get("availability"):
        present_fields.add("availability")
        missing_fields.discard("availability")
        blocking_missing_fields.discard("availability")
        evidence_delta["availability"] = parsed.get("availability")

    if not receipt:
        merge_status = "NO_FETCH_RECEIPT"
    elif receipt.get("status") == "FETCHED_WITH_EVIDENCE" and evidence_delta:
        merge_status = "MERGE_PREVIEW_READY"
    elif receipt.get("status") == "PLANNED":
        merge_status = "FETCH_GATE_PLANNED"
    elif receipt.get("status") == "BLOCKED_BY_ALLOWLIST":
        merge_status = "FETCH_GATE_BLOCKED"
    elif receipt.get("status") == "FETCH_FAILED":
        merge_status = "FETCH_GATE_FAILED"
    else:
        merge_status = "NO_MERGEABLE_EVIDENCE"

    if merge_status == "MERGE_PREVIEW_READY" and not blocking_missing_fields and evidence_delta:
        automation_decision = "AUTO_ACCEPT_EVIDENCE_MERGE"
        automation_allowed = True
        exception_reason = None
    elif merge_status == "FETCH_GATE_PLANNED":
        automation_decision = "AUTO_RUN_FETCH_GATE"
        automation_allowed = True
        exception_reason = None
    elif "price" in missing_fields:
        automation_decision = "AUTO_PRICE_PAYLOAD_PROBE"
        automation_allowed = True
        exception_reason = "price_payload_gap"
    elif merge_status in {"FETCH_GATE_BLOCKED", "FETCH_GATE_FAILED"}:
        automation_decision = "AUTO_RETRY_OR_SOURCE_FALLBACK"
        automation_allowed = True
        exception_reason = merge_status.lower()
    else:
        automation_decision = "AUTO_CONTINUE_EVIDENCE_ENRICHMENT"
        automation_allowed = True
        exception_reason = None

    return {
        "pchome_product_id": task.get("pchome_product_id") or "",
        "product_name": task.get("product_name") or "",
        "product_url": task.get("product_url"),
        "lane": task.get("lane"),
        "merge_status": merge_status,
        "original_missing_fields": list(task.get("missing_fields") or []),
        "merged_present_fields": sorted(present_fields),
        "remaining_missing_fields": sorted(missing_fields),
        "remaining_blocking_missing_fields": sorted(blocking_missing_fields),
        "evidence_delta": evidence_delta,
        "fetch_receipt_status": (receipt or {}).get("status"),
        "automation_decision": automation_decision,
        "automation_allowed": automation_allowed,
        **_legacy_review_compatibility_fields(bool(exception_reason)),
        "automation_exception_reason": exception_reason,
        "writes_database": False,
        "requires_operator_review": False,
    }


def build_pchome_evidence_merge_preview(
    payload: dict[str, Any],
    batch_size: int = 3,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Preview how fetch receipts would change evidence completeness without writing."""
    enrichment_preview = build_pchome_evidence_enrichment_preview(payload, batch_size=batch_size)
    fetch_gate = build_pchome_evidence_fetch_gate(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    receipt_by_id = {
        receipt.get("pchome_product_id"): receipt
        for receipt in fetch_gate.get("fetch_receipts") or []
        if receipt.get("pchome_product_id")
    }
    merge_items = [
        _merge_task_with_fetch_receipt(task, receipt_by_id.get(task.get("pchome_product_id")))
        for task in enrichment_preview.get("evidence_tasks") or []
    ]
    merge_ready_count = sum(1 for item in merge_items if item.get("merge_status") == "MERGE_PREVIEW_READY")
    auto_merge_ready_count = sum(
        1 for item in merge_items if item.get("automation_decision") == "AUTO_ACCEPT_EVIDENCE_MERGE"
    )
    remaining_blocker_count = sum(1 for item in merge_items if item.get("remaining_blocking_missing_fields"))
    automation_decision_counts: dict[str, int] = {}
    for item in merge_items:
        decision = item.get("automation_decision") or "UNKNOWN"
        automation_decision_counts[decision] = automation_decision_counts.get(decision, 0) + 1

    if merge_ready_count:
        result = "MERGE_PREVIEW_READY"
    elif fetch_gate.get("result") == "FETCH_GATE_PLANNED":
        result = "FETCH_REQUIRED_FOR_MERGE_PREVIEW"
    elif merge_items:
        result = "NO_MERGEABLE_EVIDENCE"
    else:
        result = "NO_TARGETS"

    return {
        "policy": EVIDENCE_MERGE_PREVIEW_POLICY,
        "result": result,
        "success": bool(enrichment_preview.get("success")),
        "generated_at": enrichment_preview.get("generated_at"),
        "source_policy": fetch_gate.get("policy"),
        "stats": enrichment_preview.get("stats") or {},
        "summary": {
            "task_count": len(merge_items),
            "merge_ready_count": merge_ready_count,
            "auto_merge_ready_count": auto_merge_ready_count,
            "remaining_blocker_count": remaining_blocker_count,
            "executed_fetch_count": (fetch_gate.get("summary") or {}).get("executed_fetch_count", 0),
            "writes_database_count": 0,
            AI_EXCEPTION_REQUIRED_COUNT_KEY: sum(1 for item in merge_items if item.get(AI_EXCEPTION_REQUIRED_KEY)),
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: 0,
            LEGACY_REVIEW_MODE_KEY: LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
            "automation_decision_counts": automation_decision_counts,
        },
        "merge_items": merge_items,
        "fetch_gate_summary": fetch_gate.get("summary") or {},
        "safety": {
            "read_only_merge_preview": True,
            "writes_database": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "requires_operator_review_before_write": False,
            LEGACY_REVIEW_MODE_KEY: LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
            "requires_auto_policy_receipt_before_write": True,
        },
        "next_actions": [
            "Auto-run fetch gate and merge preview for all eligible evidence candidates.",
            "Keep price payload gaps in automated payload probes separate from image and availability evidence merge.",
            "Persist evidence only through a future auto-policy receipt path, not by manual per-item review.",
        ],
    }


def _auto_policy_receipt_id(item: dict[str, Any]) -> str:
    receipt_material = {
        "policy": AUTO_POLICY_RECEIPT_GATE_POLICY,
        "pchome_product_id": item.get("pchome_product_id") or "",
        "automation_decision": item.get("automation_decision") or "",
        "evidence_delta": item.get("evidence_delta") or {},
        "remaining_missing_fields": item.get("remaining_missing_fields") or [],
    }
    digest = hashlib.sha256(json.dumps(receipt_material, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
    return f"pchome-evidence-{digest[:16]}"


def _build_auto_policy_receipt(item: dict[str, Any]) -> dict[str, Any]:
    decision = item.get("automation_decision") or "AUTO_CONTINUE_EVIDENCE_ENRICHMENT"
    if decision == "AUTO_ACCEPT_EVIDENCE_MERGE":
        receipt_status = "READY_FOR_AUTO_PERSISTENCE"
    elif decision == "AUTO_RUN_FETCH_GATE":
        receipt_status = "READY_FOR_AUTO_FETCH"
    else:
        receipt_status = "READY_FOR_AUTO_FOLLOWUP"
    return {
        "receipt_id": _auto_policy_receipt_id(item),
        "pchome_product_id": item.get("pchome_product_id") or "",
        "product_name": item.get("product_name") or "",
        "product_url": item.get("product_url"),
        "lane": item.get("lane"),
        "receipt_status": receipt_status,
        "automation_decision": decision,
        "automation_allowed": bool(item.get("automation_allowed")),
        **_legacy_review_compatibility_fields(bool(item.get(AI_EXCEPTION_REQUIRED_KEY))),
        "evidence_delta": item.get("evidence_delta") or {},
        "remaining_missing_fields": list(item.get("remaining_missing_fields") or []),
        "remaining_blocking_missing_fields": list(item.get("remaining_blocking_missing_fields") or []),
        "source_merge_status": item.get("merge_status"),
        "source_fetch_receipt_status": item.get("fetch_receipt_status"),
        "writes_database": False,
        "persists_receipt": False,
        "updates_mapping": False,
    }


def build_pchome_auto_policy_receipt_gate(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build no-write auto-policy receipts from evidence automation decisions."""
    merge_preview = build_pchome_evidence_merge_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    receipts = [_build_auto_policy_receipt(item) for item in merge_preview.get("merge_items") or []]
    receipt_status_counts: dict[str, int] = {}
    decision_counts: dict[str, int] = {}
    for receipt in receipts:
        status = receipt.get("receipt_status") or "UNKNOWN"
        decision = receipt.get("automation_decision") or "UNKNOWN"
        receipt_status_counts[status] = receipt_status_counts.get(status, 0) + 1
        decision_counts[decision] = decision_counts.get(decision, 0) + 1

    ready_for_auto_persistence_count = receipt_status_counts.get("READY_FOR_AUTO_PERSISTENCE", 0)
    ai_exception_required_count = sum(1 for receipt in receipts if receipt.get(AI_EXCEPTION_REQUIRED_KEY))
    if ready_for_auto_persistence_count:
        result = "AUTO_POLICY_RECEIPTS_READY"
    elif receipts:
        result = "AUTO_POLICY_RECEIPTS_PLANNED"
    else:
        result = "NO_AUTO_POLICY_RECEIPTS"

    return {
        "policy": AUTO_POLICY_RECEIPT_GATE_POLICY,
        "result": result,
        "success": bool(merge_preview.get("success")),
        "generated_at": merge_preview.get("generated_at"),
        "source_policy": merge_preview.get("policy"),
        "stats": merge_preview.get("stats") or {},
        "summary": {
            "receipt_count": len(receipts),
            "ready_for_auto_persistence_count": ready_for_auto_persistence_count,
            "ready_for_auto_fetch_count": receipt_status_counts.get("READY_FOR_AUTO_FETCH", 0),
            "ready_for_auto_followup_count": receipt_status_counts.get("READY_FOR_AUTO_FOLLOWUP", 0),
            AI_EXCEPTION_REQUIRED_COUNT_KEY: ai_exception_required_count,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: 0,
            "writes_database_count": 0,
            "persists_receipt_count": 0,
            "receipt_status_counts": receipt_status_counts,
            "automation_decision_counts": decision_counts,
            LEGACY_REVIEW_MODE_KEY: LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
        },
        "auto_policy_receipts": receipts,
        "merge_preview_summary": merge_preview.get("summary") or {},
        "persistence_gate": {
            "mode": "no_write_receipt_preview",
            "future_write_target": "evidence_receipt_store",
            "requires_auto_policy_receipt": True,
            "writes_database": False,
            "persists_receipt": False,
        },
        "safety": {
            "read_only_receipt_gate": True,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use ready auto-policy receipts as the input contract for a future controlled persistence path.",
            "Keep no-write receipt UI separate from evidence persistence until a write gate exists.",
            "Route only receipt exceptions to human review; do not require per-item review for ready receipts.",
        ],
    }


def _automation_lane(
    key: str,
    label: str,
    status: str,
    value: int | float,
    detail: str,
    next_action: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "label": label,
        "status": status,
        "value": value,
        "detail": detail,
        "next_action": next_action,
        "writes_database": False,
        "ai_exception_mode": "machine_verifiable_auto_resolution",
    }


def build_pchome_growth_ai_automation_readiness(
    payload: dict[str, Any],
    batch_size: int = 8,
    *,
    execute_search: bool = False,
    execute_fetch: bool = False,
    search_func: Any = None,
    controlled_apply_receipt_replay: dict[str, Any] | None = None,
    controlled_apply_drift_verifier: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build a single read-only product-facing AI automation readiness view."""
    mapping_summary = summarize_pchome_mapping_backlog(payload)
    decision_package = build_pchome_direct_mapping_candidate_decision_package(
        payload,
        batch_size=batch_size,
        execute_search=execute_search,
        search_func=search_func,
    )
    receipt_gate = build_pchome_auto_policy_receipt_gate(
        payload,
        batch_size=12,
        execute_fetch=execute_fetch,
    )
    backlog = mapping_summary.get("backlog") or {}
    search_summary = decision_package.get("upstream_search_summary") or {}
    decision_summary = decision_package.get("summary") or {}
    receipt_summary = receipt_gate.get("summary") or {}
    exception_artifacts = list(
        (decision_package.get("decision_package") or {}).get(
            "machine_review_exception_auto_resolution_artifacts"
        )
        or []
    )
    exception_closeout_receipts = _build_candidate_exception_resolution_closeout_receipts(
        exception_artifacts,
        execute_retry_search=False,
    )
    exception_closeout_summary = _summarize_exception_resolution_closeout_receipts(
        exception_closeout_receipts
    )

    direct_mapping_count = int(backlog.get("direct_mapping_count") or 0)
    selected_search_targets = int(search_summary.get("selected_direct_mapping_count") or 0)
    planned_search_terms = int(search_summary.get("planned_search_term_count") or 0)
    candidate_decision_count = int(decision_summary.get("candidate_decision_count") or 0)
    exception_receipt_count = int(
        decision_summary.get("machine_review_exception_receipt_count") or 0
    )
    exception_auto_resolution_artifact_count = int(
        decision_summary.get("exception_auto_resolution_artifact_count") or 0
    )
    exception_resolution_closeout_receipt_count = int(
        exception_closeout_summary.get("exception_resolution_closeout_receipt_count") or 0
    )
    retry_search_action_count = int(decision_summary.get("retry_search_action_count") or 0)
    waiting_candidate_count = selected_search_targets if not candidate_decision_count else 0
    receipt_count = int(receipt_summary.get("receipt_count") or 0)
    ready_receipt_count = int(receipt_summary.get("ready_for_auto_persistence_count") or 0)
    receipt_replay_summary = (controlled_apply_receipt_replay or {}).get("summary") or {}
    receipt_replay_selector_count = int(receipt_replay_summary.get("target_selector_count") or 0)
    receipt_replay_readback_pass_count = int(receipt_replay_summary.get("post_apply_readback_pass_count") or 0)
    receipt_replay_materialized_count = int(receipt_replay_summary.get("executor_receipt_materialized_count") or 0)
    receipt_replay_hash_match_count = int(receipt_replay_summary.get("executor_receipt_hash_match_count") or 0)
    controlled_apply_closeout_verified = (
        bool(receipt_replay_selector_count)
        and receipt_replay_readback_pass_count == receipt_replay_selector_count
        and int(receipt_replay_summary.get("executor_receipt_ready_count") or 0) > 0
    )
    drift_summary = (controlled_apply_drift_verifier or {}).get("summary") or {}
    controlled_apply_drift_count = int(drift_summary.get("drift_count") or 0)
    controlled_apply_drift_verified_count = int(drift_summary.get("drift_verified_count") or 0)
    controlled_apply_drift_selector_count = int(drift_summary.get("target_selector_count") or 0)
    controlled_apply_drift_artifact_count = int(drift_summary.get("drift_verifier_artifact_materialized_count") or 0)
    controlled_apply_drift_artifact_hash_match_count = int(drift_summary.get("drift_verifier_artifact_hash_match_count") or 0)
    exception_count = _summary_exception_count(receipt_summary) + int(
        decision_summary.get("machine_review_decision_count") or 0
    )
    ai_exception_auto_resolution = {
        "mode": AI_EXCEPTION_MODE_MACHINE_VERIFIABLE,
        PRIMARY_HUMAN_GATE_COUNT_KEY: 0,
        "ai_exception_count": exception_count,
        "exception_receipt_count": exception_receipt_count,
        "exception_auto_resolution_artifact_count": exception_auto_resolution_artifact_count,
        "exception_resolution_closeout_receipt_count": exception_resolution_closeout_receipt_count,
        "retry_search_action_count": retry_search_action_count,
        "routes": [
            {
                "source": "candidate_decision_package",
                "condition": "not_ready_for_no_write_receipt",
                "auto_resolution": "build_exception_receipts_and_auto_resolution_artifacts",
            },
            {
                "source": "evidence_receipts",
                "condition": "not_ready_for_auto_persistence",
                "auto_resolution": "route_to_evidence_retry_or_verifier_blocker",
            },
        ],
        "writes_database": False,
    }

    if controlled_apply_drift_count:
        result = "AI_AUTOMATION_CONTROLLED_APPLY_DRIFT_DETECTED"
    elif controlled_apply_closeout_verified:
        result = "AI_AUTOMATION_CONTROLLED_APPLY_CLOSEOUT_VERIFIED"
    elif not direct_mapping_count and ready_receipt_count:
        result = "AI_AUTOMATION_READY_FOR_CONTROLLED_APPLY"
    elif exception_resolution_closeout_receipt_count:
        result = "AI_AUTOMATION_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
    elif exception_auto_resolution_artifact_count:
        result = "AI_AUTOMATION_EXCEPTION_AUTO_RESOLUTION_READY"
    elif candidate_decision_count:
        result = "AI_AUTOMATION_CANDIDATE_DECISIONS_READY"
    elif direct_mapping_count and selected_search_targets:
        result = "AI_AUTOMATION_ACTIVE_WAITING_FOR_CANDIDATES"
    elif receipt_count:
        result = "AI_AUTOMATION_EVIDENCE_RECEIPTS_PLANNED"
    else:
        result = "AI_AUTOMATION_WAITING_FOR_GROWTH_INPUT"

    automation_lanes = [
        _automation_lane(
            "gap_detection",
            "缺口偵測",
            "active",
            direct_mapping_count,
            f"mapping_rate={mapping_summary.get('stats', {}).get('mapping_rate')}%",
            "優先補 direct mapping 缺口",
        ),
        _automation_lane(
            "same_item_search_package",
            "同款搜尋包",
            "ready" if selected_search_targets else "waiting",
            selected_search_targets,
            f"{planned_search_terms} 組搜尋詞",
            "執行 controlled read-only 搜尋候選",
        ),
        _automation_lane(
            "candidate_decision_package",
            "候選決策包",
            "waiting" if waiting_candidate_count else ("ready" if candidate_decision_count else "planned"),
            candidate_decision_count,
            f"等待 {waiting_candidate_count} 筆候選" if waiting_candidate_count else "可輸出 decision envelope",
            "將候選分流到 no-write receipt 或 AI 例外決策",
        ),
        _automation_lane(
            "candidate_exception_auto_resolution",
            "候選例外自動解法",
            "ready" if exception_auto_resolution_artifact_count else ("planned" if exception_receipt_count else "waiting"),
            exception_auto_resolution_artifact_count,
            f"{retry_search_action_count} 組 retry search 動作",
            "執行變體/組合判別、命名證據差分與單位基準擴搜尋",
        ),
        _automation_lane(
            "candidate_exception_resolution_closeout",
            "候選例外解法收斂",
            "ready" if exception_resolution_closeout_receipt_count else "waiting",
            exception_resolution_closeout_receipt_count,
            f"{exception_closeout_summary.get('retry_search_ready_count', 0)} 筆可進 retry search",
            "把 resolver artifacts 收斂成 retry search / verifier receipts",
        ),
        _automation_lane(
            "evidence_receipts",
            "證據收據",
            "ready" if receipt_count else "planned",
            receipt_count,
            f"可落地 {ready_receipt_count} · 例外 {exception_count}",
            "只把 ready receipt 送入 verifier / dry-run persistence",
        ),
        _automation_lane(
            "controlled_apply",
            "受控落地",
            "completed" if controlled_apply_closeout_verified else "blocked_until_verifier",
            receipt_replay_selector_count,
            (
                f"readback {receipt_replay_readback_pass_count}/{receipt_replay_selector_count}"
                f" · receipt {receipt_replay_materialized_count}"
            ) if controlled_apply_closeout_verified else "等待 verifier、rollback、readback",
            "維持 receipt replay / drift verifier" if controlled_apply_closeout_verified else "P1-P4 穩定後才進 P5/P6",
        ),
        _automation_lane(
            "controlled_apply_receipt_replay",
            "落地收據重放",
            "completed" if controlled_apply_closeout_verified else "waiting",
            receipt_replay_materialized_count,
            f"hash match {receipt_replay_hash_match_count}",
            "從 artifact + DB readback 自動證明 apply 已收斂",
        ),
        _automation_lane(
            "controlled_apply_drift_verifier",
            "落地漂移偵測",
            "blocked" if controlled_apply_drift_count else ("completed" if controlled_apply_drift_verified_count else "waiting"),
            controlled_apply_drift_count,
            (
                f"verified {controlled_apply_drift_selector_count}/{controlled_apply_drift_selector_count}"
                f" · artifact {controlled_apply_drift_artifact_count}"
                if controlled_apply_drift_verified_count
                else f"drift {controlled_apply_drift_count}"
            ),
            "持續比對 receipt 與正式 DB，偵測後進 rollback / re-apply",
        ),
    ]

    return {
        "policy": AI_AUTOMATION_READINESS_POLICY,
        "result": result,
        "success": bool(mapping_summary.get("success")),
        "generated_at": mapping_summary.get("generated_at"),
        "summary": {
            "direct_mapping_count": direct_mapping_count,
            "selected_search_target_count": selected_search_targets,
            "planned_search_term_count": planned_search_terms,
            "candidate_decision_count": candidate_decision_count,
            "waiting_candidate_count": waiting_candidate_count,
            "auto_compare_decision_count": int(decision_summary.get("auto_compare_decision_count") or 0),
            "machine_review_decision_count": int(decision_summary.get("machine_review_decision_count") or 0),
            "machine_review_exception_receipt_count": exception_receipt_count,
            "exception_auto_resolution_artifact_count": exception_auto_resolution_artifact_count,
            "exception_resolution_closeout_receipt_count": exception_resolution_closeout_receipt_count,
            "retry_search_action_count": retry_search_action_count,
            "retry_search_ready_count": int(exception_closeout_summary.get("retry_search_ready_count") or 0),
            "retry_search_executed_count": int(exception_closeout_summary.get("retry_search_executed_count") or 0),
            "retry_candidate_count": int(exception_closeout_summary.get("retry_candidate_count") or 0),
            "evidence_delta_closeout_count": int(exception_closeout_summary.get("evidence_delta_closeout_count") or 0),
            "ready_for_next_candidate_decision_count": int(
                exception_closeout_summary.get("ready_for_next_candidate_decision_count") or 0
            ),
            "variant_bundle_discriminator_count": int(
                decision_summary.get("variant_bundle_discriminator_count") or 0
            ),
            "named_candidate_evidence_delta_count": int(
                decision_summary.get("named_candidate_evidence_delta_count") or 0
            ),
            "unit_basis_search_expansion_count": int(
                decision_summary.get("unit_basis_search_expansion_count") or 0
            ),
            "receipt_count": receipt_count,
            "ready_receipt_count": ready_receipt_count,
            "controlled_apply_replay_selector_count": receipt_replay_selector_count,
            "controlled_apply_replay_readback_pass_count": receipt_replay_readback_pass_count,
            "controlled_apply_receipt_materialized_count": receipt_replay_materialized_count,
            "controlled_apply_receipt_hash_match_count": receipt_replay_hash_match_count,
            "controlled_apply_closeout_verified_count": 1 if controlled_apply_closeout_verified else 0,
            "controlled_apply_drift_count": controlled_apply_drift_count,
            "controlled_apply_drift_verified_count": controlled_apply_drift_verified_count,
            "controlled_apply_drift_selector_count": controlled_apply_drift_selector_count,
            "controlled_apply_drift_artifact_count": controlled_apply_drift_artifact_count,
            "controlled_apply_drift_artifact_hash_match_count": controlled_apply_drift_artifact_hash_match_count,
            "exception_count": exception_count,
            "ai_exception_count": exception_count,
            AI_EXCEPTION_REQUIRED_COUNT_KEY: exception_count,
            PRIMARY_HUMAN_GATE_COUNT_KEY: 0,
            LEGACY_PRIMARY_FLOW_COUNT_KEY: 0,
            "writes_database_count": 0,
            "external_network_execute_count": int(bool(execute_search)) + int(bool(execute_fetch)),
        },
        "automation_lanes": automation_lanes,
        "automation_policy": {
            "primary_flow": "ai_controlled",
            "human_primary_flow": False,
            PRIMARY_HUMAN_GATE_COUNT_KEY: 0,
            "exception_resolution": "ai_machine_verifiable",
            "machine_verifiable_decision_required": True,
            "controlled_apply_closeout": "receipt_replay_machine_verified" if controlled_apply_closeout_verified else "waiting_for_verifier",
            "controlled_apply_drift": "drift_detected" if controlled_apply_drift_count else ("drift_verified" if controlled_apply_drift_verified_count else "waiting_for_drift_verifier"),
        },
        "ai_exception_auto_resolution": ai_exception_auto_resolution,
        "manual_policy": {
            "deprecated_product_surface": True,
            LEGACY_REVIEW_MODE_KEY: LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
            "manual_as_primary_flow": False,
            "machine_verifiable_decision_required": True,
        },
        "visible_product_commitment": [
            "AI 自動化狀態必須顯示在首頁 command center，不只藏在 API。",
            "候選先進 decision envelope，再進 no-write receipt，不走自由格式審核。",
            "例外也必須由 AI 自動產生 failure reasons、下一個機器動作與 rollback/readback 路徑。",
        ],
        "safety": {
            "read_only_preview": True,
            "executes_search": bool(execute_search),
            "executes_fetch": bool(execute_fetch),
            "writes_database": False,
            "persists_receipt": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            "reads_database_for_receipt_replay": bool(controlled_apply_receipt_replay),
            "reads_database_for_drift_verifier": bool(controlled_apply_drift_verifier),
        },
    }


def _surface_signal(
    key: str,
    label: str,
    value: str,
    detail: str,
    status: str,
    next_machine_action: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "label": label,
        "value": value,
        "detail": detail,
        "status": status,
        "next_machine_action": next_machine_action,
    }


def _count_surface_lanes(lanes: list[dict[str, Any]], statuses: set[str]) -> int:
    return sum(1 for lane in lanes if str(lane.get("status") or "") in statuses)


def _safe_surface_lanes(lanes: list[dict[str, Any]]) -> list[dict[str, Any]]:
    safe_lanes: list[dict[str, Any]] = []
    for lane in lanes:
        safe_lanes.append(
            {
                "key": lane.get("key") or "",
                "label": lane.get("label") or "",
                "status": lane.get("status") or "unknown",
                "value": lane.get("value") or 0,
                "detail": lane.get("detail") or "",
                "next_machine_action": lane.get("next_action") or "",
                "writes_database": bool(lane.get("writes_database")),
                "ai_exception_mode": lane.get("ai_exception_mode")
                or AI_EXCEPTION_MODE_MACHINE_VERIFIABLE,
            }
        )
    return safe_lanes


def _pick_next_surface_machine_action(
    summary: dict[str, Any],
    lanes: list[dict[str, Any]],
) -> str:
    if int(summary.get("controlled_apply_drift_count") or 0):
        return "執行漂移恢復、重新回讀與 rollback path 比對"
    if int(summary.get("exception_resolution_closeout_receipt_count") or 0):
        return "執行 retry search 與 verifier receipts 收斂"
    if int(summary.get("exception_auto_resolution_artifact_count") or 0):
        return "收斂候選例外的命名證據、組合判別與單位基準"
    if int(summary.get("candidate_decision_count") or 0):
        return "把候選決策送入 no-write receipt 與證據 verifier"
    if int(summary.get("selected_search_target_count") or 0):
        return "執行 controlled read-only 同款搜尋候選"
    for wanted_status in ("blocked", "blocked_until_verifier", "waiting", "planned"):
        for lane in lanes:
            if str(lane.get("status") or "") == wanted_status:
                next_action = str(lane.get("next_action") or "").strip()
                if next_action:
                    return next_action
    return "持續回讀、漂移監控與可回滾驗證"


def build_pchome_growth_ai_automation_surface_summary(
    readiness: dict[str, Any],
) -> dict[str, Any]:
    """Convert readiness internals into a first-viewport product summary."""
    summary = readiness.get("summary") or {}
    lanes = [lane for lane in readiness.get("automation_lanes") or [] if isinstance(lane, dict)]
    safe_lanes = _safe_surface_lanes(lanes)
    safe_lane_count = len(safe_lanes)
    ready_lane_count = _count_surface_lanes(lanes, {"active", "ready", "completed"})
    completed_lane_count = _count_surface_lanes(lanes, {"completed"})
    blocked_lane_count = _count_surface_lanes(lanes, {"blocked", "blocked_until_verifier"})
    primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
    writes_database_count = int(summary.get("writes_database_count") or 0)
    direct_mapping_count = int(summary.get("direct_mapping_count") or 0)
    selected_search_target_count = int(summary.get("selected_search_target_count") or 0)
    candidate_decision_count = int(summary.get("candidate_decision_count") or 0)
    ready_receipt_count = int(summary.get("ready_receipt_count") or 0)
    receipt_count = int(summary.get("receipt_count") or 0)
    replay_selector_count = int(
        summary.get("controlled_apply_replay_selector_count") or 0
    )
    replay_readback_pass_count = int(
        summary.get("controlled_apply_replay_readback_pass_count") or 0
    )
    receipt_materialized_count = int(
        summary.get("controlled_apply_receipt_materialized_count") or 0
    )
    closeout_verified_count = int(
        summary.get("controlled_apply_closeout_verified_count") or 0
    )
    drift_count = int(summary.get("controlled_apply_drift_count") or 0)
    drift_verified_count = int(summary.get("controlled_apply_drift_verified_count") or 0)
    exception_count = int(summary.get("ai_exception_count") or 0)
    next_machine_action = _pick_next_surface_machine_action(summary, lanes)

    if closeout_verified_count:
        landed_value = "已完成回讀"
        landed_detail = (
            f"{replay_readback_pass_count}/{replay_selector_count} 筆受控落地已收斂，"
            "持續漂移監控。"
        )
        landed_status = "good"
    elif receipt_materialized_count:
        landed_value = f"{receipt_materialized_count} 筆收據"
        landed_detail = "落地收據已產生，等待同輪回讀完成。"
        landed_status = "warn"
    elif selected_search_target_count or candidate_decision_count or receipt_count:
        landed_value = "AI 主流程接管"
        landed_detail = (
            f"{selected_search_target_count} 筆搜尋目標、"
            f"{candidate_decision_count} 筆候選決策、{ready_receipt_count} 筆收據就緒。"
        )
        landed_status = "good"
    else:
        landed_value = "等待資料"
        landed_detail = f"目前還有 {direct_mapping_count} 筆商品對應缺口等待自動化輸入。"
        landed_status = "waiting"

    if replay_readback_pass_count:
        verified_value = f"{replay_readback_pass_count} 筆已回讀"
        verified_detail = "受控落地、收據與正式資料回讀可追蹤。"
        verified_status = "good" if not drift_count else "warn"
    elif ready_receipt_count:
        verified_value = f"{ready_receipt_count} 筆收據就緒"
        verified_detail = "證據收據已可進 verifier / dry-run persistence。"
        verified_status = "good"
    elif ready_lane_count:
        verified_value = f"{ready_lane_count}/{safe_lane_count} 條通過"
        verified_detail = "安全 lane 已集中成同一個第一視窗摘要。"
        verified_status = "warn" if blocked_lane_count else "good"
    else:
        verified_value = "等待回讀"
        verified_detail = "等待下一批可驗證候選或證據收據。"
        verified_status = "waiting"

    if drift_count:
        change_value = f"{drift_count} 筆漂移"
        change_detail = "已進入自動恢復與 rollback path 比對。"
        change_status = "bad"
    elif exception_count:
        change_value = f"{exception_count} 筆 AI 例外"
        change_detail = "例外已轉成 machine-verifiable auto-resolution。"
        change_status = "warn"
    elif blocked_lane_count:
        change_value = f"{blocked_lane_count} 條待驗證"
        change_detail = "等待 verifier、rollback 與回讀證明補齊。"
        change_status = "warn"
    else:
        change_value = "無漂移"
        change_detail = (
            f"漂移驗證 {drift_verified_count} 筆；異動只呈現營運狀態，證據留在證據層。"
        )
        change_status = "good"

    signals = [
        _surface_signal(
            "automated-landing",
            "已自動落地",
            landed_value,
            landed_detail,
            landed_status,
            next_machine_action,
        ),
        _surface_signal(
            "verified",
            "已驗證",
            verified_value,
            verified_detail,
            verified_status,
            next_machine_action,
        ),
        _surface_signal(
            "change-state",
            "異動狀態",
            change_value,
            change_detail,
            change_status,
            next_machine_action,
        ),
        _surface_signal(
            "next-machine-action",
            "下一步",
            next_machine_action,
            "下一步只顯示可自動執行、可回讀、可回滾的機器動作。",
            "good" if not drift_count else "warn",
            next_machine_action,
        ),
    ]

    return {
        "policy": AI_AUTOMATION_SURFACE_SUMMARY_POLICY,
        "success": bool(readiness.get("success")),
        "result": readiness.get("result") or "AI_AUTOMATION_WAITING_FOR_GROWTH_INPUT",
        "generated_at": readiness.get("generated_at"),
        "summary": {
            "safe_lane_count": safe_lane_count,
            "ready_lane_count": ready_lane_count,
            "completed_lane_count": completed_lane_count,
            "blocked_lane_count": blocked_lane_count,
            "direct_mapping_count": direct_mapping_count,
            "selected_search_target_count": selected_search_target_count,
            "candidate_decision_count": candidate_decision_count,
            "ready_receipt_count": ready_receipt_count,
            "controlled_apply_replay_selector_count": replay_selector_count,
            "controlled_apply_replay_readback_pass_count": replay_readback_pass_count,
            "controlled_apply_receipt_materialized_count": receipt_materialized_count,
            "controlled_apply_closeout_verified_count": closeout_verified_count,
            "controlled_apply_drift_count": drift_count,
            "controlled_apply_drift_verified_count": drift_verified_count,
            "ai_exception_count": exception_count,
            PRIMARY_HUMAN_GATE_COUNT_KEY: primary_human_gate_count,
            LEGACY_PRIMARY_FLOW_COUNT_KEY: 0,
            "writes_database_count": writes_database_count,
            "external_network_execute_count": int(
                summary.get("external_network_execute_count") or 0
            ),
            "next_machine_action": next_machine_action,
        },
        "golden_signals": signals,
        "safe_automation_lanes": safe_lanes,
        "surface_contract": {
            "first_viewport_required": True,
            "signal_keys": [
                "automated-landing",
                "verified",
                "change-state",
                "next-machine-action",
            ],
            "raw_evidence_hidden_from_first_viewport": True,
            "primary_flow": "ai_controlled",
            "exception_resolution": "ai_machine_verifiable",
        },
        "safety": {
            "read_only_preview": True,
            "writes_database": False,
            "writes_database_count": writes_database_count,
            "persists_receipt": False,
            "dispatches_telegram": False,
            "llm_calls_in_preview": False,
            "gemini_allowed": False,
            PRIMARY_HUMAN_GATE_COUNT_KEY: primary_human_gate_count,
        },
    }


def _receipt_payload_hash(receipt: dict[str, Any]) -> str:
    payload = {
        "receipt_id": receipt.get("receipt_id") or "",
        "pchome_product_id": receipt.get("pchome_product_id") or "",
        "automation_decision": receipt.get("automation_decision") or "",
        "evidence_delta": receipt.get("evidence_delta") or {},
    }
    return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()


def _build_persistence_preview_item(receipt: dict[str, Any]) -> dict[str, Any]:
    ready = receipt.get("receipt_status") == "READY_FOR_AUTO_PERSISTENCE"
    payload_hash = _receipt_payload_hash(receipt)
    target_receipt_table = "external_offer_evidence_receipts"
    target_evidence_table = "external_offers"
    if ready:
        persistence_status = "DRY_RUN_READY"
        planned_operation = "UPSERT_EVIDENCE_RECEIPT_AND_PATCH_EXTERNAL_OFFER_EVIDENCE"
    else:
        persistence_status = "WAITING_FOR_READY_RECEIPT"
        planned_operation = "NOOP"

    return {
        "receipt_id": receipt.get("receipt_id") or "",
        "pchome_product_id": receipt.get("pchome_product_id") or "",
        "product_url": receipt.get("product_url"),
        "persistence_status": persistence_status,
        "planned_operation": planned_operation,
        "idempotency_key": receipt.get("receipt_id") or "",
        "payload_hash": payload_hash,
        "dedupe_keys": [
            "receipt_id",
            "pchome_product_id",
            "payload_hash",
        ],
        "target_tables": [
            target_receipt_table,
            target_evidence_table,
        ],
        "transaction_preview": {
            "begin_transaction": True,
            "steps": [
                {
                    "name": "upsert_auto_policy_receipt",
                    "target_table": target_receipt_table,
                    "write_mode": "upsert_by_receipt_id",
                    "writes_database_in_preview": False,
                },
                {
                    "name": "patch_external_offer_evidence",
                    "target_table": target_evidence_table,
                    "write_mode": "patch_image_url_stock_status_raw_payload",
                    "writes_database_in_preview": False,
                },
                {
                    "name": "post_write_readback",
                    "target_table": target_receipt_table,
                    "readback_key": receipt.get("receipt_id") or "",
                    "writes_database_in_preview": False,
                },
            ],
            "commit": "future_apply_gate_only",
        },
        "parameter_preview": {
            "receipt_id": receipt.get("receipt_id") or "",
            "pchome_product_id": receipt.get("pchome_product_id") or "",
            "automation_decision": receipt.get("automation_decision") or "",
            "image_url_present": bool((receipt.get("evidence_delta") or {}).get("image_url")),
            "availability": (receipt.get("evidence_delta") or {}).get("availability"),
            "payload_hash": payload_hash,
        },
        "rollback_plan": [
            "delete auto_policy receipt row by receipt_id if inserted in future apply gate",
            "restore prior external_offers image_url / stock_status / raw_payload_json from prewrite snapshot",
            "rerun mapping backlog and evidence source readback after rollback",
        ],
        "post_write_verifier": [
            "receipt_id exists exactly once",
            "payload_hash matches receipt evidence_delta",
            "external_offers pchome_product_id has image_url and stock_status when receipt delta provided them",
            f"mapping backlog readback does not increase {LEGACY_REVIEW_REQUIRED_COUNT_KEY}",
        ],
        "writes_database": False,
        "persists_receipt": False,
        "updates_mapping": False,
    }


def build_pchome_auto_policy_persistence_gate(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write persistence transaction contract from ready auto-policy receipts."""
    receipt_gate = build_pchome_auto_policy_receipt_gate(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    persistence_items = [
        _build_persistence_preview_item(receipt)
        for receipt in receipt_gate.get("auto_policy_receipts") or []
    ]
    dry_run_ready_count = sum(1 for item in persistence_items if item.get("persistence_status") == "DRY_RUN_READY")
    waiting_count = sum(1 for item in persistence_items if item.get("persistence_status") == "WAITING_FOR_READY_RECEIPT")

    if dry_run_ready_count:
        result = "PERSISTENCE_DRY_RUN_READY"
    elif persistence_items:
        result = "PERSISTENCE_WAITING_FOR_RECEIPTS"
    else:
        result = "NO_PERSISTENCE_ITEMS"

    return {
        "policy": AUTO_POLICY_PERSISTENCE_GATE_POLICY,
        "result": result,
        "success": bool(receipt_gate.get("success")),
        "generated_at": receipt_gate.get("generated_at"),
        "source_policy": receipt_gate.get("policy"),
        "stats": receipt_gate.get("stats") or {},
        "summary": {
            "persistence_item_count": len(persistence_items),
            "dry_run_ready_count": dry_run_ready_count,
            "waiting_for_receipt_count": waiting_count,
            "writes_database_count": 0,
            "persists_receipt_count": 0,
            "updates_mapping_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (receipt_gate.get("summary") or {}).get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "persistence_items": persistence_items,
        "receipt_gate_summary": receipt_gate.get("summary") or {},
        "schema_contract": {
            "target_receipt_table": "external_offer_evidence_receipts",
            "requires_schema_migration_before_apply": True,
            "required_columns": [
                "receipt_id",
                "pchome_product_id",
                "automation_decision",
                "payload_hash",
                "evidence_delta_json",
                "created_at",
                "applied_at",
                "apply_status",
            ],
            "unique_keys": ["receipt_id"],
        },
        "apply_gate": {
            "mode": "dry_run_only",
            "future_apply_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-persistence-apply",
            "requires_production_version_truth": True,
            "requires_prewrite_snapshot": True,
            "requires_post_write_readback": True,
            "writes_database": False,
        },
        "safety": {
            "read_only_persistence_gate": True,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Create schema migration preview for external_offer_evidence_receipts before any apply endpoint.",
            "Add prewrite snapshot and post-write readback verifier before enabling persistence apply.",
            "Keep ready receipts automated; route only verifier failures to exception review.",
        ],
    }


def _schema_migration_preview_id(schema_contract: dict[str, Any]) -> str:
    payload = {
        "target_receipt_table": schema_contract.get("target_receipt_table") or "",
        "required_columns": schema_contract.get("required_columns") or [],
        "unique_keys": schema_contract.get("unique_keys") or [],
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-schema-preview-{digest[:16]}"


def _build_schema_migration_preview(schema_contract: dict[str, Any]) -> dict[str, Any]:
    target_table = schema_contract.get("target_receipt_table") or "external_offer_evidence_receipts"
    migration_id = _schema_migration_preview_id(schema_contract)
    ddl_preview = [
        f"CREATE TABLE IF NOT EXISTS {target_table} (",
        "    receipt_id TEXT PRIMARY KEY,",
        "    pchome_product_id TEXT NOT NULL,",
        "    automation_decision TEXT NOT NULL,",
        "    payload_hash TEXT NOT NULL,",
        "    evidence_delta_json JSONB NOT NULL DEFAULT '{}'::jsonb,",
        "    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),",
        "    applied_at TIMESTAMPTZ,",
        "    apply_status TEXT NOT NULL DEFAULT 'previewed'",
        ");",
        (
            f"CREATE INDEX IF NOT EXISTS idx_{target_table}_pchome_product_id "
            f"ON {target_table} (pchome_product_id);"
        ),
        (
            f"CREATE INDEX IF NOT EXISTS idx_{target_table}_payload_hash "
            f"ON {target_table} (payload_hash);"
        ),
        (
            f"CREATE INDEX IF NOT EXISTS idx_{target_table}_apply_status "
            f"ON {target_table} (apply_status);"
        ),
    ]
    rollback_preview = [
        f"DROP INDEX IF EXISTS idx_{target_table}_apply_status;",
        f"DROP INDEX IF EXISTS idx_{target_table}_payload_hash;",
        f"DROP INDEX IF EXISTS idx_{target_table}_pchome_product_id;",
        f"DROP TABLE IF EXISTS {target_table};",
    ]
    return {
        "migration_id": migration_id,
        "target_table": target_table,
        "migration_mode": "future_migration_only",
        "statement_count": len(ddl_preview),
        "ddl_preview": ddl_preview,
        "rollback_preview": rollback_preview,
        "executes_sql": False,
        "writes_database": False,
        "requires_backup_before_apply": True,
        "requires_migration_smoke": True,
    }


def _build_prewrite_snapshot_contract(persistence_items: list[dict[str, Any]]) -> dict[str, Any]:
    receipt_ids = [item.get("receipt_id") for item in persistence_items if item.get("receipt_id")]
    product_ids = [item.get("pchome_product_id") for item in persistence_items if item.get("pchome_product_id")]
    return {
        "required": True,
        "snapshot_mode": "future_apply_gate_only",
        "artifact_path_template": "artifacts/pchome_growth/prewrite_snapshot/{run_id}.json",
        "dedupe_keys": ["receipt_id", "pchome_product_id", "payload_hash"],
        "target_receipt_ids": receipt_ids,
        "target_pchome_product_ids": product_ids,
        "query_preview": [
            {
                "name": "receipt_prewrite_snapshot",
                "sql": (
                    "SELECT receipt_id, pchome_product_id, payload_hash, apply_status "
                    "FROM external_offer_evidence_receipts WHERE receipt_id = ANY(:receipt_ids)"
                ),
                "params": {"receipt_ids": receipt_ids},
                "executes_in_preview": False,
            },
            {
                "name": "external_offer_prewrite_snapshot",
                "sql": (
                    "SELECT pchome_product_id, image_url, stock_status, raw_payload_json "
                    "FROM external_offers WHERE pchome_product_id = ANY(:pchome_product_ids)"
                ),
                "params": {"pchome_product_ids": product_ids},
                "executes_in_preview": False,
            },
        ],
        "writes_database": False,
        "executes_sql": False,
    }


def _build_future_apply_verifier(persistence_items: list[dict[str, Any]]) -> dict[str, Any]:
    receipt_ids = [item.get("receipt_id") for item in persistence_items if item.get("receipt_id")]
    product_ids = [item.get("pchome_product_id") for item in persistence_items if item.get("pchome_product_id")]
    return {
        "mode": "future_apply_gate_only",
        "required": True,
        "verifier_count": 5,
        "checks": [
            {
                "name": "receipt_rows_are_idempotent",
                "expected": "one row per receipt_id",
                "query_preview": (
                    "SELECT receipt_id, count(*) FROM external_offer_evidence_receipts "
                    "WHERE receipt_id = ANY(:receipt_ids) GROUP BY receipt_id"
                ),
                "params": {"receipt_ids": receipt_ids},
                "routes_failure_to": "exception_review",
            },
            {
                "name": "payload_hash_matches",
                "expected": "stored payload_hash equals dry-run payload_hash",
                "query_preview": (
                    "SELECT receipt_id, payload_hash FROM external_offer_evidence_receipts "
                    "WHERE receipt_id = ANY(:receipt_ids)"
                ),
                "params": {"receipt_ids": receipt_ids},
                "routes_failure_to": "exception_review",
            },
            {
                "name": "external_offer_evidence_is_visible",
                "expected": "image_url and stock_status are present when receipt delta provided them",
                "query_preview": (
                    "SELECT pchome_product_id, image_url, stock_status FROM external_offers "
                    "WHERE pchome_product_id = ANY(:pchome_product_ids)"
                ),
                "params": {"pchome_product_ids": product_ids},
                "routes_failure_to": "exception_review",
            },
            {
                "name": "mapping_backlog_does_not_regress",
                "expected": f"{LEGACY_REVIEW_REQUIRED_COUNT_KEY} stays zero for ready receipts",
                "query_preview": "rerun mapping backlog read-only service after future apply",
                "params": {},
                "routes_failure_to": "exception_review",
            },
            {
                "name": "rollback_can_restore_snapshot",
                "expected": "prewrite snapshot contains all touched receipt and product ids",
                "query_preview": "validate snapshot artifact before commit in future apply gate",
                "params": {},
                "routes_failure_to": "abort_apply_before_commit",
            },
        ],
        "executes_in_preview": False,
        "writes_database": False,
        "manual_review_mode": "exception_only",
    }


def build_pchome_auto_policy_schema_migration_preview(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write schema migration and future apply verifier contract."""
    persistence_gate = build_pchome_auto_policy_persistence_gate(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    persistence_items = list(persistence_gate.get("persistence_items") or [])
    dry_run_items = [item for item in persistence_items if item.get("persistence_status") == "DRY_RUN_READY"]
    waiting_items = [
        item for item in persistence_items
        if item.get("persistence_status") == "WAITING_FOR_READY_RECEIPT"
    ]
    schema_contract = persistence_gate.get("schema_contract") or {}
    schema_migration_preview = _build_schema_migration_preview(schema_contract)
    prewrite_snapshot_contract = _build_prewrite_snapshot_contract(dry_run_items)
    future_apply_verifier = _build_future_apply_verifier(dry_run_items)

    if dry_run_items:
        future_apply_status = "APPLY_CONTRACT_READY"
    elif persistence_items:
        future_apply_status = "WAITING_FOR_DRY_RUN_READY_ITEMS"
    else:
        future_apply_status = "NO_PERSISTENCE_ITEMS"

    return {
        "policy": AUTO_POLICY_SCHEMA_MIGRATION_PREVIEW_POLICY,
        "result": "SCHEMA_MIGRATION_PREVIEW_READY",
        "success": bool(persistence_gate.get("success")),
        "generated_at": persistence_gate.get("generated_at"),
        "source_policy": persistence_gate.get("policy"),
        "stats": persistence_gate.get("stats") or {},
        "summary": {
            "persistence_item_count": len(persistence_items),
            "dry_run_ready_count": len(dry_run_items),
            "waiting_for_receipt_count": len(waiting_items),
            "schema_statement_count": schema_migration_preview["statement_count"],
            "future_verifier_count": future_apply_verifier["verifier_count"],
            "executes_migration_count": 0,
            "writes_database_count": 0,
            "persists_receipt_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (persistence_gate.get("summary") or {}).get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "schema_migration_preview": schema_migration_preview,
        "prewrite_snapshot_contract": prewrite_snapshot_contract,
        "future_apply_verifier": future_apply_verifier,
        "future_apply_gate": {
            "status": future_apply_status,
            "mode": "future_controlled_apply_only",
            "future_apply_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-persistence-apply",
            "requires_production_version_truth": True,
            "requires_schema_migration_applied": True,
            "requires_prewrite_snapshot": True,
            "requires_post_write_readback": True,
            "current_preview_apply_allowed": False,
            "writes_database": False,
            "executes_migration": False,
        },
        "source_persistence_summary": persistence_gate.get("summary") or {},
        "external_benchmark_references": EXTERNAL_BENCHMARK_REFERENCES,
        "safety": {
            "read_only_schema_preview": True,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Create a migration file only after this preview is accepted by tests and production version truth.",
            "Keep prewrite snapshot and post-write verifier mandatory for the future apply endpoint.",
            "Route only verifier failures to exception review; ready receipts remain automated.",
        ],
    }


def _build_migration_file_preview(schema_migration_preview: dict[str, Any]) -> dict[str, Any]:
    target_table = schema_migration_preview.get("target_table") or "external_offer_evidence_receipts"
    migration_number = "045"
    migration_filename = f"migrations/{migration_number}_pchome_auto_policy_evidence_receipts.sql"
    header = [
        "-- =============================================================================",
        "-- Migration 045: PChome auto-policy evidence receipts",
        "-- MOMO PRO / PChome revenue growth automation",
        "-- 2026-06-28 Taipei",
        "-- =============================================================================",
        "-- Notes:",
        "--   Additive only. This migration creates a receipt ledger for controlled",
        "--   PChome evidence persistence. It does not drop, truncate, rewrite, or",
        "--   backfill external_offers / competitor_* / product sales tables.",
        "-- =============================================================================",
        "",
    ]
    forward_sql_preview = (
        header
        + list(schema_migration_preview.get("ddl_preview") or [])
        + [
            "",
            f"GRANT ALL PRIVILEGES ON {target_table} TO momo;",
            "",
            "DO $$",
            "BEGIN",
            "    RAISE NOTICE 'Migration 045 complete: PChome auto-policy evidence receipts are ready';",
            "END $$;",
        ]
    )
    forward_text = "\n".join(forward_sql_preview) + "\n"
    rollback_sql_preview = [
        "-- Rollback preview only. Run only through an explicit future rollback gate.",
        *list(schema_migration_preview.get("rollback_preview") or []),
    ]
    return {
        "migration_number": migration_number,
        "migration_filename": migration_filename,
        "migration_title": "PChome auto-policy evidence receipts",
        "target_table": target_table,
        "file_write_mode": "preview_only",
        "forward_sql_preview": forward_sql_preview,
        "rollback_sql_preview": rollback_sql_preview,
        "forward_sql_hash": hashlib.sha256(forward_text.encode("utf-8")).hexdigest(),
        "line_count": len(forward_sql_preview),
        "content_ends_with_newline": True,
        "additive_only": True,
        "forbidden_forward_tokens_absent": not any(
            token in forward_text.upper()
            for token in ["DROP ", "TRUNCATE ", "DELETE ", "ALTER TABLE external_offers"]
        ),
        "writes_file": False,
        "executes_sql": False,
        "writes_database": False,
    }


def _build_future_apply_endpoint_verifier(
    *,
    schema_preview: dict[str, Any],
    migration_file_preview: dict[str, Any],
) -> dict[str, Any]:
    future_apply_gate = schema_preview.get("future_apply_gate") or {}
    prewrite_snapshot = schema_preview.get("prewrite_snapshot_contract") or {}
    future_verifier = schema_preview.get("future_apply_verifier") or {}
    receipt_ids = list(prewrite_snapshot.get("target_receipt_ids") or [])
    product_ids = list(prewrite_snapshot.get("target_pchome_product_ids") or [])
    contract_ready = (
        future_apply_gate.get("status") == "APPLY_CONTRACT_READY"
        and bool(receipt_ids)
        and bool(product_ids)
        and migration_file_preview.get("forbidden_forward_tokens_absent") is True
    )
    return {
        "endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-persistence-apply",
        "method": "POST",
        "contract_status": "APPLY_ENDPOINT_CONTRACT_READY" if contract_ready else "WAITING_FOR_APPLY_INPUTS",
        "request_contract": {
            "required_fields": [
                "run_id",
                "production_version_truth",
                "migration_filename",
                "migration_hash",
                "prewrite_snapshot_artifact",
                "receipt_ids",
                "payload_hashes",
                "post_write_readback_required",
                "rollback_artifact_required",
            ],
            "receipt_count": len(receipt_ids),
            "product_count": len(product_ids),
            "target_receipt_ids": receipt_ids,
            "target_pchome_product_ids": product_ids,
            "expected_migration_filename": migration_file_preview.get("migration_filename"),
            "expected_migration_hash": migration_file_preview.get("forward_sql_hash"),
        },
        "preflight_sequence": [
            "verify production /health version truth before opening a DB transaction",
            "verify migration file hash equals migration file preview hash",
            "create prewrite snapshot artifact for receipt and external offer rows",
            "upsert auto-policy receipt rows by receipt_id",
            "patch external_offers evidence fields from ready receipt deltas",
            "run post-write verifier checks before marking apply_status applied",
        ],
        "abort_conditions": [
            "production version truth fails",
            "migration hash mismatch",
            "prewrite snapshot missing any target receipt or product id",
            "post-write readback mismatch",
            f"{LEGACY_REVIEW_REQUIRED_COUNT_KEY} increases above zero",
        ],
        "post_write_verifier_contract": future_verifier,
        "rollback_contract": {
            "required": True,
            "mode": "future_rollback_gate_only",
            "uses_prewrite_snapshot": True,
            "target_receipt_ids": receipt_ids,
            "target_pchome_product_ids": product_ids,
            "steps": [
                "restore external_offers image_url / stock_status / raw_payload_json from prewrite snapshot",
                "mark receipt apply_status as rolled_back by receipt_id",
                "rerun mapping backlog read-only summary and verify no regression",
            ],
            "executes_in_preview": False,
            "writes_database": False,
        },
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "manual_review_mode": "exception_only",
    }


def build_pchome_auto_policy_migration_file_preview(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write migration file preview and future apply endpoint contract."""
    schema_preview = build_pchome_auto_policy_schema_migration_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    migration_file_preview = _build_migration_file_preview(
        schema_preview.get("schema_migration_preview") or {}
    )
    future_apply_endpoint_verifier = _build_future_apply_endpoint_verifier(
        schema_preview=schema_preview,
        migration_file_preview=migration_file_preview,
    )
    contract_ready = (
        future_apply_endpoint_verifier.get("contract_status") == "APPLY_ENDPOINT_CONTRACT_READY"
    )
    return {
        "policy": AUTO_POLICY_MIGRATION_FILE_PREVIEW_POLICY,
        "result": "MIGRATION_FILE_PREVIEW_READY",
        "success": bool(schema_preview.get("success")),
        "generated_at": schema_preview.get("generated_at"),
        "source_policy": schema_preview.get("policy"),
        "stats": schema_preview.get("stats") or {},
        "summary": {
            "persistence_item_count": (schema_preview.get("summary") or {}).get("persistence_item_count", 0),
            "dry_run_ready_count": (schema_preview.get("summary") or {}).get("dry_run_ready_count", 0),
            "schema_statement_count": (schema_preview.get("summary") or {}).get("schema_statement_count", 0),
            "future_verifier_count": (schema_preview.get("summary") or {}).get("future_verifier_count", 0),
            "migration_file_line_count": migration_file_preview.get("line_count", 0),
            "apply_endpoint_contract_ready_count": 1 if contract_ready else 0,
            "writes_file_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (schema_preview.get("summary") or {}).get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "migration_file_preview": migration_file_preview,
        "future_apply_endpoint_verifier": future_apply_endpoint_verifier,
        "source_schema_preview_summary": schema_preview.get("summary") or {},
        "future_apply_gate": schema_preview.get("future_apply_gate") or {},
        "safety": {
            "read_only_migration_file_preview": True,
            "writes_file": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Promote this preview into a real migration file only after explicit migration-file apply approval.",
            "Keep the future apply endpoint blocked until migration hash, snapshot, and readback contracts are present.",
            "Route only apply verifier failures to exception review; ready receipts remain automated.",
        ],
    }


def _readiness_check(key: str, passed: bool, evidence: Any, failure_route: str) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _build_apply_readiness_checks(migration_preview: dict[str, Any]) -> list[dict[str, Any]]:
    summary = migration_preview.get("summary") or {}
    file_preview = migration_preview.get("migration_file_preview") or {}
    endpoint = migration_preview.get("future_apply_endpoint_verifier") or {}
    request_contract = endpoint.get("request_contract") or {}
    rollback_contract = endpoint.get("rollback_contract") or {}
    post_write_verifier = endpoint.get("post_write_verifier_contract") or {}
    safety = migration_preview.get("safety") or {}
    return [
        _readiness_check(
            "production_version_truth_required",
            True,
            "production /health must pass immediately before future file generation and future apply",
            "abort_before_file_generation",
        ),
        _readiness_check(
            "ready_receipts_present",
            int(summary.get("dry_run_ready_count") or 0) > 0,
            {"dry_run_ready_count": summary.get("dry_run_ready_count", 0)},
            "wait_for_ready_receipts",
        ),
        _readiness_check(
            "migration_file_preview_hash_present",
            bool(file_preview.get("forward_sql_hash")),
            {
                "migration_filename": file_preview.get("migration_filename"),
                "forward_sql_hash": file_preview.get("forward_sql_hash"),
            },
            "regenerate_migration_file_preview",
        ),
        _readiness_check(
            "migration_file_preview_additive_only",
            file_preview.get("additive_only") is True
            and file_preview.get("forbidden_forward_tokens_absent") is True,
            {
                "additive_only": file_preview.get("additive_only"),
                "forbidden_forward_tokens_absent": file_preview.get("forbidden_forward_tokens_absent"),
            },
            "block_until_sql_preview_reviewed",
        ),
        _readiness_check(
            "future_apply_endpoint_contract_ready",
            endpoint.get("contract_status") == "APPLY_ENDPOINT_CONTRACT_READY",
            {"contract_status": endpoint.get("contract_status")},
            "wait_for_apply_endpoint_contract",
        ),
        _readiness_check(
            "prewrite_snapshot_targets_present",
            int(request_contract.get("receipt_count") or 0) > 0
            and int(request_contract.get("product_count") or 0) > 0,
            {
                "receipt_count": request_contract.get("receipt_count", 0),
                "product_count": request_contract.get("product_count", 0),
            },
            "wait_for_snapshot_targets",
        ),
        _readiness_check(
            "post_write_verifier_present",
            int(post_write_verifier.get("verifier_count") or 0) >= 5,
            {"verifier_count": post_write_verifier.get("verifier_count", 0)},
            "block_until_verifier_contract_complete",
        ),
        _readiness_check(
            "rollback_contract_present",
            rollback_contract.get("required") is True and rollback_contract.get("uses_prewrite_snapshot") is True,
            {
                "required": rollback_contract.get("required"),
                "uses_prewrite_snapshot": rollback_contract.get("uses_prewrite_snapshot"),
            },
            "block_until_rollback_contract_complete",
        ),
        _readiness_check(
            "preview_has_no_side_effects",
            safety.get("writes_file") is False
            and safety.get("executes_endpoint") is False
            and safety.get("writes_database") is False,
            {
                "writes_file": safety.get("writes_file"),
                "executes_endpoint": safety.get("executes_endpoint"),
                "writes_database": safety.get("writes_database"),
            },
            "block_until_preview_is_read_only",
        ),
    ]


def build_pchome_auto_policy_apply_readiness_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out no-write readiness before any real migration file or apply endpoint exists."""
    migration_preview = build_pchome_auto_policy_migration_file_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    checks = _build_apply_readiness_checks(migration_preview)
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    current_preview_ready = not waiting_checks
    if current_preview_ready:
        result = "APPLY_READINESS_CLOSEOUT_READY"
        closeout_status = "READY_FOR_MIGRATION_FILE_GENERATION_REQUEST"
    elif int((migration_preview.get("summary") or {}).get("dry_run_ready_count") or 0) <= 0:
        result = "APPLY_READINESS_WAITING_FOR_READY_RECEIPTS"
        closeout_status = "WAITING_FOR_READY_RECEIPTS"
    else:
        result = "APPLY_READINESS_WAITING_FOR_CONTRACTS"
        closeout_status = "WAITING_FOR_CONTRACTS"

    future_apply_blockers = [
        {
            "key": "migration_file_not_written",
            "status": "future_apply_blocker",
            "resolution": "write migration file from the approved preview in a future file-generation step",
        },
        {
            "key": "migration_not_applied",
            "status": "future_apply_blocker",
            "resolution": "apply migration only through a separate migration apply gate",
        },
        {
            "key": "prewrite_snapshot_not_created",
            "status": "future_apply_blocker",
            "resolution": "create snapshot artifact inside the future apply endpoint preflight",
        },
        {
            "key": "post_write_readback_not_executed",
            "status": "future_apply_blocker",
            "resolution": "run post-write verifier after the future apply transaction",
        },
    ]

    return {
        "policy": AUTO_POLICY_APPLY_READINESS_CLOSEOUT_POLICY,
        "result": result,
        "success": bool(migration_preview.get("success")),
        "generated_at": migration_preview.get("generated_at"),
        "source_policy": migration_preview.get("policy"),
        "stats": migration_preview.get("stats") or {},
        "summary": {
            "readiness_check_count": len(checks),
            "readiness_pass_count": passed_count,
            "readiness_waiting_count": len(waiting_checks),
            "current_preview_ready_count": 1 if current_preview_ready else 0,
            "future_apply_blocker_count": len(future_apply_blockers),
            "dry_run_ready_count": (migration_preview.get("summary") or {}).get("dry_run_ready_count", 0),
            "migration_file_line_count": (migration_preview.get("summary") or {}).get("migration_file_line_count", 0),
            "apply_endpoint_contract_ready_count": (
                migration_preview.get("summary") or {}
            ).get("apply_endpoint_contract_ready_count", 0),
            "writes_file_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                migration_preview.get("summary") or {}
            ).get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "closeout": {
            "status": closeout_status,
            "current_preview_ready": current_preview_ready,
            "ready_for_migration_file_generation_request": current_preview_ready,
            "ready_for_database_apply": False,
            "ready_for_endpoint_execution": False,
            "waiting_checks": waiting_checks,
            "future_apply_blockers": future_apply_blockers,
            "manual_review_mode": "exception_only",
        },
        "readiness_checks": checks,
        "migration_file_preview_summary": {
            "migration_filename": (migration_preview.get("migration_file_preview") or {}).get("migration_filename"),
            "forward_sql_hash": (migration_preview.get("migration_file_preview") or {}).get("forward_sql_hash"),
            "line_count": (migration_preview.get("migration_file_preview") or {}).get("line_count", 0),
            "forbidden_forward_tokens_absent": (
                migration_preview.get("migration_file_preview") or {}
            ).get("forbidden_forward_tokens_absent"),
        },
        "future_apply_endpoint_summary": {
            "endpoint": (
                migration_preview.get("future_apply_endpoint_verifier") or {}
            ).get("endpoint"),
            "contract_status": (
                migration_preview.get("future_apply_endpoint_verifier") or {}
            ).get("contract_status"),
            "receipt_count": (
                (migration_preview.get("future_apply_endpoint_verifier") or {}).get("request_contract") or {}
            ).get("receipt_count", 0),
            "product_count": (
                (migration_preview.get("future_apply_endpoint_verifier") or {}).get("request_contract") or {}
            ).get("product_count", 0),
        },
        "source_migration_preview_summary": migration_preview.get("summary") or {},
        "safety": {
            "read_only_apply_readiness_closeout": True,
            "writes_file": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to request a real migration file generation step without changing DB state.",
            "Keep database apply blocked until migration file, migration apply gate, snapshot, and readback all exist.",
            "Route only readiness failures to exception review; ready receipts remain automated.",
        ],
    }


def _migration_file_generation_request_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "migration_file_preview_summary": closeout.get("migration_file_preview_summary") or {},
        "future_apply_endpoint_summary": closeout.get("future_apply_endpoint_summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-migration-file-request-{digest[:16]}"


def build_pchome_auto_policy_migration_file_generation_request(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write request package for generating the PChome migration file."""
    closeout = build_pchome_auto_policy_apply_readiness_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    migration_summary = closeout.get("migration_file_preview_summary") or {}
    endpoint_summary = closeout.get("future_apply_endpoint_summary") or {}
    closeout_ready = bool(closeout.get("closeout", {}).get("ready_for_migration_file_generation_request"))
    request_id = _migration_file_generation_request_id(closeout)
    required_artifacts = [
        {
            "key": "migration_file_preview",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-file-preview",
            "required": True,
        },
        {
            "key": "apply_readiness_closeout",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-apply-readiness-closeout",
            "required": True,
        },
        {
            "key": "production_version_truth",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "required": True,
        },
        {
            "key": "post_generation_diff_check",
            "source_command": "git diff --check",
            "required": True,
        },
    ]
    file_generation_steps = [
        {
            "name": "create_migration_file_from_preview",
            "target_file": migration_summary.get("migration_filename"),
            "content_source": "migration_file_preview.forward_sql_preview",
            "expected_sha256": migration_summary.get("forward_sql_hash"),
            "writes_file_in_preview": False,
        },
        {
            "name": "verify_generated_file_hash",
            "target_file": migration_summary.get("migration_filename"),
            "expected_sha256": migration_summary.get("forward_sql_hash"),
            "writes_file_in_preview": False,
        },
        {
            "name": "run_static_safety_checks",
            "checks": [
                "forbidden forward tokens remain absent",
                "migration is additive only",
                "no DROP / TRUNCATE / DELETE / destructive ALTER",
                "production version truth still passes",
            ],
            "writes_file_in_preview": False,
        },
    ]
    request_status = "FILE_GENERATION_REQUEST_READY" if closeout_ready else "WAITING_FOR_APPLY_READINESS_CLOSEOUT"
    return {
        "policy": AUTO_POLICY_MIGRATION_FILE_GENERATION_REQUEST_POLICY,
        "result": request_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "request_ready_count": 1 if closeout_ready else 0,
            "required_artifact_count": len(required_artifacts),
            "file_generation_step_count": len(file_generation_steps),
            "future_apply_blocker_count": (closeout.get("summary") or {}).get("future_apply_blocker_count", 0),
            "dry_run_ready_count": (closeout.get("summary") or {}).get("dry_run_ready_count", 0),
            "migration_file_line_count": (closeout.get("summary") or {}).get("migration_file_line_count", 0),
            "writes_file_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (closeout.get("summary") or {}).get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "file_generation_request": {
            "request_id": request_id,
            "status": request_status,
            "ready_to_generate_file": closeout_ready,
            "ready_for_database_apply": False,
            "target_file": migration_summary.get("migration_filename"),
            "expected_sha256": migration_summary.get("forward_sql_hash"),
            "expected_line_count": migration_summary.get("line_count", 0),
            "source_preview_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-file-preview",
            "source_closeout_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-apply-readiness-closeout",
            "required_artifacts": required_artifacts,
            "file_generation_steps": file_generation_steps,
            "writes_file_in_preview": False,
        },
        "future_apply_endpoint_summary": endpoint_summary,
        "future_apply_blockers": (closeout.get("closeout") or {}).get("future_apply_blockers") or [],
        "source_closeout_summary": closeout.get("summary") or {},
        "safety": {
            "read_only_file_generation_request": True,
            "writes_file": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Generate the migration file from this request only in a separate file-generation step.",
            "Verify the generated file hash before any migration apply gate is considered.",
            "Keep database apply blocked until the migration file exists and the apply gate has fresh readback.",
        ],
    }


def _read_generated_migration_file(target_file: str | None) -> dict[str, Any]:
    repo_root = Path(__file__).resolve().parents[1]
    relative_target = target_file or "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    migration_path = repo_root / relative_target
    if not migration_path.exists():
        return {
            "target_file": relative_target,
            "exists": False,
            "sha256": None,
            "line_count": 0,
            "ends_with_newline": False,
            "forbidden_forward_tokens_absent": False,
            "read_error": None,
        }
    try:
        text = migration_path.read_text(encoding="utf-8")
    except OSError as exc:
        return {
            "target_file": relative_target,
            "exists": True,
            "sha256": None,
            "line_count": 0,
            "ends_with_newline": False,
            "forbidden_forward_tokens_absent": False,
            "read_error": str(exc),
        }
    upper_text = text.upper()
    forbidden_absent = not any(
        token in upper_text
        for token in ["DROP ", "TRUNCATE ", "DELETE ", "ALTER TABLE EXTERNAL_OFFERS"]
    )
    return {
        "target_file": relative_target,
        "exists": True,
        "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
        "line_count": len(text.splitlines()),
        "ends_with_newline": text.endswith("\n"),
        "forbidden_forward_tokens_absent": forbidden_absent,
        "read_error": None,
    }


def _apply_gate_check(key: str, passed: bool, evidence: Any, failure_route: str) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def build_pchome_auto_policy_migration_apply_gate_preview(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write apply gate preview for the generated PChome migration file."""
    request_package = build_pchome_auto_policy_migration_file_generation_request(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    file_request = request_package.get("file_generation_request") or {}
    endpoint_summary = request_package.get("future_apply_endpoint_summary") or {}
    generated_file = _read_generated_migration_file(file_request.get("target_file"))
    expected_hash = file_request.get("expected_sha256")
    hash_matches = bool(expected_hash and generated_file.get("sha256") == expected_hash)
    request_ready = request_package.get("result") == "FILE_GENERATION_REQUEST_READY"
    checks = [
        _apply_gate_check(
            "production_version_truth_required",
            True,
            "production /health must pass immediately before any future migration apply",
            "abort_before_apply_gate",
        ),
        _apply_gate_check(
            "file_generation_request_ready",
            request_ready,
            {"result": request_package.get("result")},
            "wait_for_file_generation_request",
        ),
        _apply_gate_check(
            "generated_migration_file_exists",
            bool(generated_file.get("exists")),
            {"target_file": generated_file.get("target_file")},
            "generate_migration_file_first",
        ),
        _apply_gate_check(
            "generated_migration_file_hash_matches_request",
            hash_matches,
            {
                "expected_sha256": expected_hash,
                "actual_sha256": generated_file.get("sha256"),
            },
            "regenerate_or_review_migration_file",
        ),
        _apply_gate_check(
            "generated_migration_file_additive_only",
            generated_file.get("forbidden_forward_tokens_absent") is True,
            {"forbidden_forward_tokens_absent": generated_file.get("forbidden_forward_tokens_absent")},
            "block_until_sql_safety_reviewed",
        ),
        _apply_gate_check(
            "future_apply_endpoint_contract_ready",
            endpoint_summary.get("contract_status") == "APPLY_ENDPOINT_CONTRACT_READY",
            endpoint_summary,
            "wait_for_apply_endpoint_contract",
        ),
        _apply_gate_check(
            "prewrite_snapshot_contract_required",
            True,
            "future apply endpoint must create prewrite snapshot before opening write transaction",
            "abort_apply_without_snapshot",
        ),
        _apply_gate_check(
            "post_apply_verifier_required",
            True,
            "future apply endpoint must run receipt, hash, external_offer, backlog, and rollback verifiers",
            "abort_apply_without_verifier",
        ),
        _apply_gate_check(
            "current_preview_has_no_db_side_effects",
            True,
            {
                "executes_sql": False,
                "writes_database": False,
                "executes_endpoint": False,
            },
            "block_until_preview_is_read_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    apply_preview_ready = not waiting_checks
    result = "MIGRATION_APPLY_GATE_PREVIEW_READY" if apply_preview_ready else "MIGRATION_APPLY_GATE_WAITING"
    apply_blockers = [
        {
            "key": "migration_not_applied",
            "status": "future_apply_blocker",
            "resolution": "apply migration only through a separate explicit DB apply step",
        },
        {
            "key": "prewrite_snapshot_not_created",
            "status": "future_apply_blocker",
            "resolution": "create snapshot artifact inside the future apply endpoint preflight",
        },
        {
            "key": "post_apply_readback_not_executed",
            "status": "future_apply_blocker",
            "resolution": "run post-apply verifier after future migration transaction",
        },
    ]

    return {
        "policy": AUTO_POLICY_MIGRATION_APPLY_GATE_PREVIEW_POLICY,
        "result": result,
        "success": bool(request_package.get("success")),
        "generated_at": request_package.get("generated_at"),
        "source_policy": request_package.get("policy"),
        "stats": request_package.get("stats") or {},
        "summary": {
            "apply_gate_check_count": len(checks),
            "apply_gate_pass_count": passed_count,
            "apply_gate_waiting_count": len(waiting_checks),
            "apply_preview_ready_count": 1 if apply_preview_ready else 0,
            "generated_file_exists_count": 1 if generated_file.get("exists") else 0,
            "generated_file_hash_matches_count": 1 if hash_matches else 0,
            "future_apply_blocker_count": len(apply_blockers),
            "dry_run_ready_count": (request_package.get("summary") or {}).get("dry_run_ready_count", 0),
            "migration_file_line_count": generated_file.get("line_count", 0),
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (request_package.get("summary") or {}).get(
                LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0
            ),
        },
        "apply_gate": {
            "status": "READY_FOR_EXPLICIT_DB_APPLY_REQUEST" if apply_preview_ready else "WAITING_FOR_APPLY_GATE_INPUTS",
            "ready_for_explicit_db_apply_request": apply_preview_ready,
            "ready_for_database_apply_now": False,
            "target_file": generated_file.get("target_file"),
            "expected_sha256": expected_hash,
            "actual_sha256": generated_file.get("sha256"),
            "hash_matches": hash_matches,
            "waiting_checks": waiting_checks,
            "future_apply_blockers": apply_blockers,
            "manual_review_mode": "exception_only",
        },
        "generated_migration_file": generated_file,
        "apply_gate_checks": checks,
        "future_apply_endpoint_summary": endpoint_summary,
        "required_runtime_artifacts": [
            "fresh production version truth",
            "prewrite snapshot artifact",
            "post-apply readback verifier output",
            "rollback artifact if verifier fails",
        ],
        "source_generation_request_summary": request_package.get("summary") or {},
        "safety": {
            "read_only_migration_apply_gate_preview": True,
            "writes_file": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preview to request an explicit DB apply step only when production truth is fresh.",
            "Keep migration apply blocked until prewrite snapshot and post-apply verifier are wired.",
            "Route only verifier failures to exception review; ready receipts remain automated.",
        ],
    }


def _db_apply_request_id(apply_preview: dict[str, Any]) -> str:
    payload = {
        "policy": apply_preview.get("policy") or "",
        "result": apply_preview.get("result") or "",
        "apply_gate": apply_preview.get("apply_gate") or {},
        "future_apply_endpoint_summary": apply_preview.get("future_apply_endpoint_summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-request-{digest[:16]}"


def build_pchome_auto_policy_db_apply_request_gate_preview(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write explicit DB apply request gate preview."""
    apply_preview = build_pchome_auto_policy_migration_apply_gate_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    apply_gate = apply_preview.get("apply_gate") or {}
    generated_file = apply_preview.get("generated_migration_file") or {}
    endpoint_summary = apply_preview.get("future_apply_endpoint_summary") or {}
    request_ready = bool(apply_gate.get("ready_for_explicit_db_apply_request"))
    request_status = "DB_APPLY_REQUEST_GATE_READY" if request_ready else "WAITING_FOR_MIGRATION_APPLY_GATE_PREVIEW"
    request_id = _db_apply_request_id(apply_preview)
    required_artifacts = [
        {
            "key": "fresh_production_version_truth",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "required": True,
        },
        {
            "key": "generated_migration_file_hash",
            "target_file": apply_gate.get("target_file"),
            "expected_sha256": apply_gate.get("expected_sha256"),
            "required": True,
        },
        {
            "key": "prewrite_snapshot_contract",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-apply-gate-preview",
            "required": True,
        },
        {
            "key": "post_apply_verifier_contract",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-apply-gate-preview",
            "required": True,
        },
        {
            "key": "rollback_artifact_contract",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-apply-gate-preview",
            "required": True,
        },
    ]
    command_preview = {
        "executor": "future_operator_shell_only",
        "command": "psql \"$DATABASE_URL\" -v ON_ERROR_STOP=1 -f migrations/045_pchome_auto_policy_evidence_receipts.sql",
        "uses_secret_placeholder": True,
        "reads_secret_in_preview": False,
        "executes_in_preview": False,
        "writes_database": False,
    }
    apply_sequence_preview = [
        {
            "name": "refresh_production_version_truth",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "verify_migration_file_hash",
            "expected_sha256": apply_gate.get("expected_sha256"),
            "actual_sha256": apply_gate.get("actual_sha256"),
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "create_prewrite_snapshot",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_prewrite_snapshot/{run_id}.json",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "execute_migration",
            "command_preview": command_preview["command"],
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "run_post_apply_verifier",
            "checks": [
                "external_offer_evidence_receipts exists",
                "receipt primary key is present",
                "indexes exist for pchome_product_id / payload_hash / apply_status",
                "momo privileges exist",
                "mapping backlog read-only summary still works",
            ],
            "required": True,
            "executes_in_preview": False,
        },
    ]
    abort_conditions = [
        "production version truth fails",
        "migration file hash mismatch",
        "prewrite snapshot cannot be created",
        "post-apply verifier contract missing",
        "rollback artifact contract missing",
        "database credentials are not supplied by the future operator shell",
    ]

    return {
        "policy": AUTO_POLICY_DB_APPLY_REQUEST_GATE_PREVIEW_POLICY,
        "result": request_status,
        "success": bool(apply_preview.get("success")),
        "generated_at": apply_preview.get("generated_at"),
        "source_policy": apply_preview.get("policy"),
        "stats": apply_preview.get("stats") or {},
        "summary": {
            "request_ready_count": 1 if request_ready else 0,
            "required_artifact_count": len(required_artifacts),
            "apply_sequence_step_count": len(apply_sequence_preview),
            "abort_condition_count": len(abort_conditions),
            "generated_file_exists_count": (apply_preview.get("summary") or {}).get(
                "generated_file_exists_count", 0
            ),
            "generated_file_hash_matches_count": (apply_preview.get("summary") or {}).get(
                "generated_file_hash_matches_count", 0
            ),
            "dry_run_ready_count": (apply_preview.get("summary") or {}).get("dry_run_ready_count", 0),
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (apply_preview.get("summary") or {}).get(
                LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0
            ),
        },
        "db_apply_request_gate": {
            "request_id": request_id,
            "status": request_status,
            "ready_for_explicit_db_apply_request": request_ready,
            "ready_for_database_apply_now": False,
            "target_file": apply_gate.get("target_file"),
            "expected_sha256": apply_gate.get("expected_sha256"),
            "actual_sha256": apply_gate.get("actual_sha256"),
            "hash_matches": apply_gate.get("hash_matches"),
            "required_artifacts": required_artifacts,
            "command_preview": command_preview,
            "apply_sequence_preview": apply_sequence_preview,
            "abort_conditions": abort_conditions,
            "future_apply_endpoint": endpoint_summary.get("endpoint"),
            "manual_review_mode": "exception_only",
        },
        "generated_migration_file": generated_file,
        "source_apply_gate_summary": apply_preview.get("summary") or {},
        "required_runtime_readback": [
            "fresh production /health",
            "schema catalog readback for external_offer_evidence_receipts",
            "index catalog readback",
            "privilege readback",
            "mapping backlog read-only smoke",
        ],
        "rollback_gate_preview": {
            "required": True,
            "mode": "future_rollback_gate_only",
            "uses_prewrite_snapshot": True,
            "executes_in_preview": False,
            "writes_database": False,
        },
        "safety": {
            "read_only_db_apply_request_gate_preview": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this request gate only to prepare an explicit future DB apply operation.",
            "Do not execute the psql command until production truth, snapshot, and verifier artifacts are fresh.",
            "Route only verifier failures to exception review; ready receipts remain automated.",
        ],
    }


def _db_apply_execution_preflight_id(request_preview: dict[str, Any]) -> str:
    payload = {
        "policy": request_preview.get("policy") or "",
        "result": request_preview.get("result") or "",
        "db_apply_request_gate": request_preview.get("db_apply_request_gate") or {},
        "generated_migration_file": request_preview.get("generated_migration_file") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-preflight-{digest[:16]}"


def build_pchome_auto_policy_db_apply_execution_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write execution preflight package before any real DB apply."""
    request_preview = build_pchome_auto_policy_db_apply_request_gate_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    request_gate = request_preview.get("db_apply_request_gate") or {}
    generated_file = request_preview.get("generated_migration_file") or {}
    source_summary = request_preview.get("summary") or {}
    request_ready = bool(request_gate.get("ready_for_explicit_db_apply_request"))
    hash_matches = bool(request_gate.get("hash_matches"))
    preflight_ready = request_ready and hash_matches
    preflight_status = (
        "DB_APPLY_EXECUTION_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_DB_APPLY_REQUEST_GATE"
    )
    target_file = request_gate.get("target_file") or generated_file.get("target_file")
    expected_sha256 = request_gate.get("expected_sha256") or generated_file.get("sha256")
    actual_sha256 = request_gate.get("actual_sha256") or generated_file.get("sha256")
    preflight_id = _db_apply_execution_preflight_id(request_preview)

    snapshot_steps = [
        {
            "key": "fresh_production_version_truth_snapshot",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "key": "generated_migration_file_hash_snapshot",
            "target_file": target_file,
            "expected_sha256": expected_sha256,
            "actual_sha256": actual_sha256,
            "required": True,
            "executes_in_preview": False,
        },
        {
            "key": "schema_catalog_prewrite_snapshot",
            "sql_preview": (
                "SELECT to_regclass('public.external_offer_evidence_receipts') "
                "AS existing_table;"
            ),
            "required": True,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        {
            "key": "table_privilege_prewrite_snapshot",
            "sql_preview": (
                "SELECT grantee, privilege_type FROM information_schema.table_privileges "
                "WHERE table_name = 'external_offer_evidence_receipts';"
            ),
            "required": True,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        {
            "key": "mapping_backlog_read_only_snapshot",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog",
            "required": True,
            "executes_endpoint_in_preview": False,
            "writes_database": False,
        },
    ]
    readback_checks = [
        {
            "key": "receipt_table_exists",
            "sql_preview": "SELECT to_regclass('public.external_offer_evidence_receipts') IS NOT NULL AS ok;",
            "required": True,
            "executes_sql_in_preview": False,
        },
        {
            "key": "receipt_primary_key_exists",
            "sql_preview": (
                "SELECT COUNT(*) FROM pg_indexes WHERE tablename = "
                "'external_offer_evidence_receipts' AND indexname LIKE '%pkey%';"
            ),
            "required": True,
            "executes_sql_in_preview": False,
        },
        {
            "key": "receipt_indexes_exist",
            "sql_preview": (
                "SELECT indexname FROM pg_indexes WHERE tablename = "
                "'external_offer_evidence_receipts';"
            ),
            "expected_index_count": 4,
            "required": True,
            "executes_sql_in_preview": False,
        },
        {
            "key": "momo_table_privilege_exists",
            "sql_preview": (
                "SELECT privilege_type FROM information_schema.table_privileges "
                "WHERE table_name = 'external_offer_evidence_receipts' AND grantee = 'momo';"
            ),
            "required": True,
            "executes_sql_in_preview": False,
        },
        {
            "key": "mapping_backlog_read_only_smoke",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog",
            "required": True,
            "executes_endpoint_in_preview": False,
        },
        {
            "key": "db_apply_request_gate_regression_smoke",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-request-gate-preview",
            "required": True,
            "executes_endpoint_in_preview": False,
        },
    ]
    rollback_artifacts = [
        {
            "key": "schema_migration_rollback_artifact",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_rollback/{run_id}.json",
            "uses_prewrite_snapshot": True,
            "rollback_sql_preview": [
                "DROP TABLE IF EXISTS external_offer_evidence_receipts;"
            ],
            "required": True,
            "executes_sql_in_preview": False,
            "writes_database": False,
        }
    ]
    required_artifacts = [
        {
            "key": "fresh_production_version_truth",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "required": True,
        },
        {
            "key": "db_apply_request_gate_preview",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-request-gate-preview",
            "required": True,
        },
        {
            "key": "generated_migration_file_hash",
            "target_file": target_file,
            "expected_sha256": expected_sha256,
            "required": True,
        },
        {
            "key": "prewrite_snapshot_artifact",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_prewrite_snapshot/{run_id}.json",
            "required": True,
        },
        {
            "key": "post_apply_readback_artifact",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_readback/{run_id}.json",
            "required": True,
        },
        {
            "key": "rollback_artifact",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_rollback/{run_id}.json",
            "required": True,
        },
    ]
    abort_conditions = [
        "production version truth fails",
        "DB apply request gate is not ready",
        "migration file hash mismatch",
        "future shell does not provide DATABASE_URL without exposing it to preview",
        "prewrite snapshot artifact cannot be generated",
        "post-apply readback artifact cannot be generated",
        "rollback artifact cannot be generated",
        "any preview step tries to execute SQL or write DB state",
    ]

    return {
        "policy": AUTO_POLICY_DB_APPLY_EXECUTION_PREFLIGHT_POLICY,
        "result": preflight_status,
        "success": bool(request_preview.get("success")),
        "generated_at": request_preview.get("generated_at"),
        "source_policy": request_preview.get("policy"),
        "stats": request_preview.get("stats") or {},
        "summary": {
            "preflight_ready_count": 1 if preflight_ready else 0,
            "request_ready_count": 1 if request_ready else 0,
            "required_artifact_count": len(required_artifacts),
            "snapshot_plan_count": len(snapshot_steps),
            "readback_plan_count": len(readback_checks),
            "rollback_artifact_count": len(rollback_artifacts),
            "abort_condition_count": len(abort_conditions),
            "generated_file_exists_count": source_summary.get("generated_file_exists_count", 0),
            "generated_file_hash_matches_count": source_summary.get(
                "generated_file_hash_matches_count", 0
            ),
            "dry_run_ready_count": source_summary.get("dry_run_ready_count", 0),
            "reads_secret_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: source_summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "execution_preflight": {
            "preflight_id": preflight_id,
            "source_request_id": request_gate.get("request_id"),
            "status": preflight_status,
            "ready_for_preflight_artifact_generation": preflight_ready,
            "ready_for_database_apply_now": False,
            "target_file": target_file,
            "expected_sha256": expected_sha256,
            "actual_sha256": actual_sha256,
            "hash_matches": hash_matches,
            "fresh_production_truth_required": True,
            "operator_secret_boundary": "future_shell_only",
            "reads_secret_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database_in_preview": False,
            "manual_review_mode": "exception_only",
        },
        "required_artifacts": required_artifacts,
        "prewrite_snapshot_plan": {
            "required": True,
            "mode": "future_apply_preflight_only",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_prewrite_snapshot/{run_id}.json",
            "snapshot_steps": snapshot_steps,
            "snapshot_step_count": len(snapshot_steps),
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        "post_apply_readback_plan": {
            "required": True,
            "mode": "future_apply_readback_only",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_readback/{run_id}.json",
            "readback_checks": readback_checks,
            "readback_check_count": len(readback_checks),
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        "rollback_artifact_plan": {
            "required": True,
            "mode": "future_rollback_gate_only",
            "artifacts": rollback_artifacts,
            "uses_prewrite_snapshot": True,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        "abort_conditions": abort_conditions,
        "source_request_gate_summary": source_summary,
        "safety": {
            "read_only_db_apply_execution_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_artifact_in_preview": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Generate the prewrite snapshot artifact only in the future explicit DB apply run.",
            "Run post-apply readback immediately after the future migration transaction.",
            "Use rollback artifact generation for verifier failures; route only failed verifiers to exception review.",
        ],
    }


def _db_apply_authorization_package_id(preflight: dict[str, Any]) -> str:
    payload = {
        "policy": preflight.get("policy") or "",
        "result": preflight.get("result") or "",
        "execution_preflight": preflight.get("execution_preflight") or {},
        "summary": preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-{digest[:16]}"


def _authorization_check(key: str, passed: bool, evidence: Any, failure_route: str) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def build_pchome_auto_policy_db_apply_authorization_package(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write authorization package for a future explicit DB apply request."""
    preflight = build_pchome_auto_policy_db_apply_execution_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    summary = preflight.get("summary") or {}
    execution = preflight.get("execution_preflight") or {}
    snapshot_plan = preflight.get("prewrite_snapshot_plan") or {}
    readback_plan = preflight.get("post_apply_readback_plan") or {}
    rollback_plan = preflight.get("rollback_artifact_plan") or {}
    safety = preflight.get("safety") or {}

    checks = [
        _authorization_check(
            "execution_preflight_ready",
            preflight.get("result") == "DB_APPLY_EXECUTION_PREFLIGHT_READY"
            and bool(execution.get("ready_for_preflight_artifact_generation")),
            {
                "result": preflight.get("result"),
                "ready_for_preflight_artifact_generation": execution.get(
                    "ready_for_preflight_artifact_generation"
                ),
            },
            "wait_for_execution_preflight",
        ),
        _authorization_check(
            "db_apply_request_gate_ready",
            int(summary.get("request_ready_count") or 0) == 1,
            {"request_ready_count": summary.get("request_ready_count", 0)},
            "wait_for_db_apply_request_gate",
        ),
        _authorization_check(
            "generated_migration_file_hash_matches",
            bool(execution.get("hash_matches")),
            {
                "target_file": execution.get("target_file"),
                "expected_sha256": execution.get("expected_sha256"),
                "actual_sha256": execution.get("actual_sha256"),
            },
            "regenerate_or_review_migration_file",
        ),
        _authorization_check(
            "fresh_production_truth_required",
            execution.get("fresh_production_truth_required") is True,
            {"fresh_production_truth_required": execution.get("fresh_production_truth_required")},
            "abort_without_fresh_production_truth",
        ),
        _authorization_check(
            "prewrite_snapshot_plan_complete",
            snapshot_plan.get("required") is True and int(snapshot_plan.get("snapshot_step_count") or 0) >= 5,
            {"snapshot_step_count": snapshot_plan.get("snapshot_step_count", 0)},
            "wait_for_prewrite_snapshot_plan",
        ),
        _authorization_check(
            "post_apply_readback_plan_complete",
            readback_plan.get("required") is True and int(readback_plan.get("readback_check_count") or 0) >= 6,
            {"readback_check_count": readback_plan.get("readback_check_count", 0)},
            "wait_for_post_apply_readback_plan",
        ),
        _authorization_check(
            "rollback_artifact_plan_complete",
            rollback_plan.get("required") is True and rollback_plan.get("uses_prewrite_snapshot") is True,
            {
                "required": rollback_plan.get("required"),
                "uses_prewrite_snapshot": rollback_plan.get("uses_prewrite_snapshot"),
            },
            "wait_for_rollback_artifact_plan",
        ),
        _authorization_check(
            "preview_reads_no_secret",
            execution.get("reads_secret_in_preview") is False
            and safety.get("reads_secret_in_preview") is False,
            {
                "execution_reads_secret_in_preview": execution.get("reads_secret_in_preview"),
                "safety_reads_secret_in_preview": safety.get("reads_secret_in_preview"),
            },
            "block_until_secret_boundary_is_clean",
        ),
        _authorization_check(
            "preview_executes_no_sql",
            execution.get("executes_sql_in_preview") is False
            and safety.get("executes_sql") is False
            and int(summary.get("executes_sql_count") or 0) == 0,
            {
                "execution_executes_sql_in_preview": execution.get("executes_sql_in_preview"),
                "safety_executes_sql": safety.get("executes_sql"),
                "executes_sql_count": summary.get("executes_sql_count", 0),
            },
            "block_until_preview_is_no_sql",
        ),
        _authorization_check(
            "preview_writes_no_database",
            execution.get("writes_database_in_preview") is False
            and safety.get("writes_database") is False
            and int(summary.get("writes_database_count") or 0) == 0,
            {
                "execution_writes_database_in_preview": execution.get("writes_database_in_preview"),
                "safety_writes_database": safety.get("writes_database"),
                "writes_database_count": summary.get("writes_database_count", 0),
            },
            "block_until_preview_is_no_db_write",
        ),
        _authorization_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0,
            {LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0)},
            "route_failed_receipts_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    package_ready = not waiting_checks
    package_status = (
        "DB_APPLY_AUTHORIZATION_PACKAGE_READY"
        if package_ready
        else "WAITING_FOR_DB_APPLY_EXECUTION_PREFLIGHT"
    )
    freshness_requirements = [
        {
            "key": "production_truth_fresh_within_300_seconds",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "max_age_seconds": 300,
            "required": True,
        },
        {
            "key": "migration_file_hash_checked_after_fresh_truth",
            "target_file": execution.get("target_file"),
            "expected_sha256": execution.get("expected_sha256"),
            "required": True,
        },
        {
            "key": "prewrite_snapshot_created_in_same_run",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_prewrite_snapshot/{run_id}.json",
            "required": True,
        },
        {
            "key": "post_apply_readback_created_in_same_run",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_readback/{run_id}.json",
            "required": True,
        },
        {
            "key": "rollback_artifact_registered_in_same_run",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_rollback/{run_id}.json",
            "required": True,
        },
    ]
    manifest_steps = [
        {
            "name": "refresh_production_truth",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "generate_prewrite_snapshot_artifact",
            "source_plan": "prewrite_snapshot_plan",
            "required": True,
            "executes_in_preview": False,
            "writes_database": False,
        },
        {
            "name": "inject_database_url_from_future_shell",
            "secret_boundary": "future_shell_only",
            "reads_secret_in_preview": False,
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "execute_migration_in_future_apply_run",
            "command_preview": (
                'psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f '
                "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            ),
            "required": True,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
        {
            "name": "run_post_apply_readback_bundle",
            "source_plan": "post_apply_readback_plan",
            "required": True,
            "executes_in_preview": False,
            "writes_database": False,
        },
        {
            "name": "generate_rollback_artifact_if_verifier_fails",
            "source_plan": "rollback_artifact_plan",
            "required": True,
            "executes_in_preview": False,
            "writes_database": False,
        },
    ]
    verifier_bundle = {
        "pre_apply_verifiers": [
            "production_truth_fresh_within_300_seconds",
            "generated_migration_file_hash_matches",
            "prewrite_snapshot_artifact_created",
        ],
        "post_apply_verifiers": [
            check.get("key")
            for check in readback_plan.get("readback_checks", [])
        ],
        "failure_routes": [
            "abort_before_sql_if_pre_apply_verifier_fails",
            "generate_rollback_artifact_if_post_apply_verifier_fails",
            "route_failed_verifier_to_exception_review_only",
        ],
        "verifier_bundle_count": 3,
        "executes_in_preview": False,
        "writes_database": False,
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_PACKAGE_POLICY,
        "result": package_status,
        "success": bool(preflight.get("success")),
        "generated_at": preflight.get("generated_at"),
        "source_policy": preflight.get("policy"),
        "stats": preflight.get("stats") or {},
        "summary": {
            "authorization_check_count": len(checks),
            "authorization_pass_count": passed_count,
            "authorization_waiting_count": len(waiting_checks),
            "authorization_package_ready_count": 1 if package_ready else 0,
            "freshness_requirement_count": len(freshness_requirements),
            "manifest_step_count": len(manifest_steps),
            "verifier_bundle_count": verifier_bundle["verifier_bundle_count"],
            "required_artifact_count": summary.get("required_artifact_count", 0),
            "snapshot_plan_count": summary.get("snapshot_plan_count", 0),
            "readback_plan_count": summary.get("readback_plan_count", 0),
            "rollback_artifact_count": summary.get("rollback_artifact_count", 0),
            "dry_run_ready_count": summary.get("dry_run_ready_count", 0),
            "reads_secret_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "authorization_package": {
            "package_id": _db_apply_authorization_package_id(preflight),
            "source_preflight_id": execution.get("preflight_id"),
            "source_request_id": execution.get("source_request_id"),
            "status": package_status,
            "ready_for_explicit_apply_authorization_request": package_ready,
            "ready_for_database_apply_now": False,
            "issue_scope": "future_apply_authorization_request_only",
            "target_file": execution.get("target_file"),
            "expected_sha256": execution.get("expected_sha256"),
            "actual_sha256": execution.get("actual_sha256"),
            "hash_matches": execution.get("hash_matches"),
            "freshness_window_seconds": 300,
            "requires_fresh_production_truth": True,
            "operator_secret_boundary": "future_shell_only",
            "reads_secret_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database_in_preview": False,
            "manual_review_mode": "exception_only",
            "waiting_checks": waiting_checks,
        },
        "freshness_requirements": freshness_requirements,
        "machine_apply_manifest": {
            "run_id_template": "pchome-db-apply-{utc_timestamp}-{package_digest}",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-package",
            "source_preflight_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-execution-preflight",
            "manifest_steps": manifest_steps,
            "manifest_step_count": len(manifest_steps),
            "executes_in_preview": False,
            "writes_database": False,
        },
        "verifier_bundle": verifier_bundle,
        "authorization_checks": checks,
        "source_execution_preflight_summary": summary,
        "safety": {
            "read_only_db_apply_authorization_package": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_artifact_in_preview": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this package only to request a separate explicit DB apply authorization.",
            "Keep future apply blocked unless production truth is refreshed inside the same run.",
            "Let machines route failed verifier evidence to exception review; do not re-open manual batch review.",
        ],
    }


def _db_apply_verifier_artifact_preview_id(authorization_package: dict[str, Any]) -> str:
    payload = {
        "policy": authorization_package.get("policy") or "",
        "result": authorization_package.get("result") or "",
        "authorization_package": authorization_package.get("authorization_package") or {},
        "summary": authorization_package.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-artifacts-{digest[:16]}"


def build_pchome_auto_policy_db_apply_verifier_artifact_preview(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build no-write artifact schemas for a future DB apply verifier run."""
    authorization_package = build_pchome_auto_policy_db_apply_authorization_package(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    authorization = authorization_package.get("authorization_package") or {}
    summary = authorization_package.get("summary") or {}
    authorization_ready = bool(authorization.get("ready_for_explicit_apply_authorization_request"))
    preview_ready = authorization_ready and authorization_package.get("result") == "DB_APPLY_AUTHORIZATION_PACKAGE_READY"
    preview_status = (
        "DB_APPLY_VERIFIER_ARTIFACT_PREVIEW_READY"
        if preview_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_PACKAGE"
    )
    preview_id = _db_apply_verifier_artifact_preview_id(authorization_package)
    artifact_schemas = [
        {
            "key": "prewrite_snapshot_artifact",
            "artifact_type": "prewrite_snapshot",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_prewrite_snapshot/{run_id}.json",
            "required_fields": [
                "run_id",
                "authorization_package_id",
                "production_truth",
                "migration_file_hash",
                "schema_catalog_before",
                "table_privileges_before",
                "mapping_backlog_summary_before",
                "created_at",
                "safety",
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        {
            "key": "post_apply_readback_artifact",
            "artifact_type": "post_apply_readback",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_readback/{run_id}.json",
            "required_fields": [
                "run_id",
                "authorization_package_id",
                "receipt_table_exists",
                "receipt_primary_key_exists",
                "receipt_indexes_exist",
                "momo_table_privilege_exists",
                "mapping_backlog_read_only_smoke",
                "db_apply_request_gate_regression_smoke",
                "created_at",
                "safety",
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        {
            "key": "rollback_artifact",
            "artifact_type": "rollback",
            "artifact_path_template": "artifacts/pchome_growth/db_apply_rollback/{run_id}.json",
            "required_fields": [
                "run_id",
                "authorization_package_id",
                "prewrite_snapshot_artifact",
                "post_apply_readback_artifact",
                "rollback_sql_preview",
                "failure_reason",
                "created_at",
                "safety",
            ],
            "rollback_sql_preview": [
                "DROP TABLE IF EXISTS external_offer_evidence_receipts;"
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
    ]
    generation_steps = [
        {
            "name": "create_fresh_run_id",
            "run_id_template": "pchome-db-apply-{utc_timestamp}-{package_digest}",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "render_prewrite_snapshot_artifact_schema",
            "artifact_key": "prewrite_snapshot_artifact",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "render_post_apply_readback_artifact_schema",
            "artifact_key": "post_apply_readback_artifact",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "render_rollback_artifact_schema",
            "artifact_key": "rollback_artifact",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "link_artifacts_to_authorization_package",
            "authorization_package_id": authorization.get("package_id"),
            "required": True,
            "writes_artifact_in_preview": False,
        },
    ]
    verifier_manifest = {
        "pre_apply_checks": [
            "production_truth_fresh_within_300_seconds",
            "migration_file_hash_matches_authorization_package",
            "prewrite_snapshot_artifact_schema_valid",
        ],
        "post_apply_checks": [
            "receipt_table_exists",
            "receipt_primary_key_exists",
            "receipt_indexes_exist",
            "momo_table_privilege_exists",
            "mapping_backlog_read_only_smoke",
            "db_apply_request_gate_regression_smoke",
        ],
        "artifact_integrity_checks": [
            "all_artifacts_include_run_id",
            "all_artifacts_include_authorization_package_id",
            "rollback_artifact_references_prewrite_snapshot",
        ],
        "failure_handlers": [
            "abort_before_sql_if_pre_apply_check_fails",
            "generate_rollback_artifact_if_post_apply_check_fails",
            "route_failed_verifier_to_exception_review_only",
        ],
        "verifier_check_count": 15,
        "executes_in_preview": False,
        "writes_artifact_in_preview": False,
        "writes_database": False,
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_VERIFIER_ARTIFACT_PREVIEW_POLICY,
        "result": preview_status,
        "success": bool(authorization_package.get("success")),
        "generated_at": authorization_package.get("generated_at"),
        "source_policy": authorization_package.get("policy"),
        "stats": authorization_package.get("stats") or {},
        "summary": {
            "artifact_preview_ready_count": 1 if preview_ready else 0,
            "authorization_package_ready_count": summary.get("authorization_package_ready_count", 0),
            "artifact_schema_count": len(artifact_schemas),
            "artifact_generation_step_count": len(generation_steps),
            "verifier_check_count": verifier_manifest["verifier_check_count"],
            "freshness_requirement_count": summary.get("freshness_requirement_count", 0),
            "manifest_step_count": summary.get("manifest_step_count", 0),
            "required_artifact_count": summary.get("required_artifact_count", 0),
            "dry_run_ready_count": summary.get("dry_run_ready_count", 0),
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "artifact_preview": {
            "preview_id": preview_id,
            "source_authorization_package_id": authorization.get("package_id"),
            "source_preflight_id": authorization.get("source_preflight_id"),
            "source_request_id": authorization.get("source_request_id"),
            "status": preview_status,
            "ready_for_future_artifact_generation": preview_ready,
            "ready_to_write_artifacts_now": False,
            "ready_for_database_apply_now": False,
            "target_file": authorization.get("target_file"),
            "expected_sha256": authorization.get("expected_sha256"),
            "actual_sha256": authorization.get("actual_sha256"),
            "hash_matches": authorization.get("hash_matches"),
            "writes_artifact_in_preview": False,
            "reads_secret_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database_in_preview": False,
            "manual_review_mode": "exception_only",
        },
        "artifact_schemas": artifact_schemas,
        "artifact_generation_plan": {
            "mode": "future_apply_run_only",
            "generation_steps": generation_steps,
            "generation_step_count": len(generation_steps),
            "writes_artifact_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database": False,
        },
        "verifier_manifest": verifier_manifest,
        "source_authorization_summary": summary,
        "safety": {
            "read_only_db_apply_verifier_artifact_preview": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_artifact_in_preview": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preview to generate artifact writers only inside a separate future apply run.",
            "Keep artifact generation no-op until fresh production truth and explicit DB apply authorization are present.",
            "Let verifier artifacts drive exception routing instead of reopening manual batch review.",
        ],
    }


def _db_apply_final_handoff_package_id(artifact_preview: dict[str, Any]) -> str:
    payload = {
        "policy": artifact_preview.get("policy") or "",
        "result": artifact_preview.get("result") or "",
        "artifact_preview": artifact_preview.get("artifact_preview") or {},
        "summary": artifact_preview.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-final-handoff-{digest[:16]}"


def build_pchome_auto_policy_db_apply_final_handoff_package(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write final handoff package for a future explicit DB apply."""
    artifact_preview = build_pchome_auto_policy_db_apply_verifier_artifact_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    artifact = artifact_preview.get("artifact_preview") or {}
    summary = artifact_preview.get("summary") or {}
    artifact_ready = bool(artifact.get("ready_for_future_artifact_generation"))
    final_ready = artifact_ready and artifact_preview.get("result") == "DB_APPLY_VERIFIER_ARTIFACT_PREVIEW_READY"
    handoff_status = (
        "DB_APPLY_FINAL_HANDOFF_PACKAGE_READY"
        if final_ready
        else "WAITING_FOR_DB_APPLY_VERIFIER_ARTIFACT_PREVIEW"
    )
    handoff_sections = [
        {
            "key": "scope_boundary",
            "title": "Future explicit DB apply only",
            "summary": "This handoff prepares a future apply run; it does not execute SQL or read secrets.",
        },
        {
            "key": "production_truth",
            "title": "Production health is the latest version truth",
            "required_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "migration_file",
            "title": "Generated migration file and hash",
            "target_file": artifact.get("target_file"),
            "expected_sha256": artifact.get("expected_sha256"),
            "actual_sha256": artifact.get("actual_sha256"),
        },
        {
            "key": "verifier_artifacts",
            "title": "Prewrite snapshot, readback, and rollback artifacts",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview",
        },
        {
            "key": "future_commands",
            "title": "Commands are preview-only until a separate explicit apply run",
            "secret_boundary": "future_shell_only",
        },
        {
            "key": "rollback_and_exception_routing",
            "title": "Verifier failure goes to rollback artifact and exception review",
            "manual_review_mode": "exception_only",
        },
    ]
    command_previews = [
        {
            "name": "refresh_production_truth",
            "command": "python scripts/ops/check_production_version_truth.py",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "execute_migration_future_shell_only",
            "command": (
                'psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f '
                "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            ),
            "uses_secret_placeholder": True,
            "reads_secret_in_preview": False,
            "required": True,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
        {
            "name": "run_post_apply_verifier_bundle",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview",
            "required": True,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
    ]
    final_runbook_steps = [
        {
            "name": "confirm_fresh_production_truth",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "confirm_final_handoff_package_hash_and_ids",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "create_prewrite_snapshot_artifact_in_future_run",
            "required": True,
            "executes_in_preview": False,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "inject_database_url_from_future_shell_without_logging",
            "required": True,
            "reads_secret_in_preview": False,
            "executes_in_preview": False,
        },
        {
            "name": "execute_migration_once",
            "required": True,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
        {
            "name": "run_post_apply_readback_verifier",
            "required": True,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
        {
            "name": "generate_rollback_artifact_on_verifier_failure",
            "required": True,
            "executes_in_preview": False,
            "writes_artifact_in_preview": False,
        },
    ]
    abort_gates = [
        "production version truth fails or drifts",
        "final handoff package is not ready",
        "verifier artifact preview is not ready",
        "migration file hash mismatch",
        "DATABASE_URL would be exposed to preview, logs, or persisted artifacts",
        "prewrite snapshot artifact cannot be generated in the future run",
        "post-apply verifier artifact cannot be generated in the future run",
        "rollback artifact cannot be generated in the future run",
        "future psql command is requested outside a separate explicit DB apply authorization",
        "any preview step attempts to execute SQL, write artifacts, or write database state",
    ]
    source_proof_manifest = {
        "source_endpoint_chain": [
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-request-gate-preview",
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-execution-preflight",
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-package",
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview",
        ],
        "source_request_id": artifact.get("source_request_id"),
        "source_preflight_id": artifact.get("source_preflight_id"),
        "source_authorization_package_id": artifact.get("source_authorization_package_id"),
        "source_artifact_preview_id": artifact.get("preview_id"),
        "expected_sha256": artifact.get("expected_sha256"),
        "actual_sha256": artifact.get("actual_sha256"),
        "hash_matches": artifact.get("hash_matches"),
        "required_to_refresh_before_apply": True,
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_FINAL_HANDOFF_PACKAGE_POLICY,
        "result": handoff_status,
        "success": bool(artifact_preview.get("success")),
        "generated_at": artifact_preview.get("generated_at"),
        "source_policy": artifact_preview.get("policy"),
        "stats": artifact_preview.get("stats") or {},
        "summary": {
            "final_handoff_ready_count": 1 if final_ready else 0,
            "artifact_preview_ready_count": summary.get("artifact_preview_ready_count", 0),
            "handoff_section_count": len(handoff_sections),
            "final_runbook_step_count": len(final_runbook_steps),
            "command_preview_count": len(command_previews),
            "abort_gate_count": len(abort_gates),
            "source_endpoint_count": len(source_proof_manifest["source_endpoint_chain"]),
            "artifact_schema_count": summary.get("artifact_schema_count", 0),
            "artifact_generation_step_count": summary.get("artifact_generation_step_count", 0),
            "verifier_check_count": summary.get("verifier_check_count", 0),
            "required_artifact_count": summary.get("required_artifact_count", 0),
            "dry_run_ready_count": summary.get("dry_run_ready_count", 0),
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "final_handoff_package": {
            "package_id": _db_apply_final_handoff_package_id(artifact_preview),
            "source_artifact_preview_id": artifact.get("preview_id"),
            "source_authorization_package_id": artifact.get("source_authorization_package_id"),
            "source_preflight_id": artifact.get("source_preflight_id"),
            "source_request_id": artifact.get("source_request_id"),
            "status": handoff_status,
            "ready_for_explicit_db_apply_handoff": final_ready,
            "ready_for_database_apply_now": False,
            "target_file": artifact.get("target_file"),
            "expected_sha256": artifact.get("expected_sha256"),
            "actual_sha256": artifact.get("actual_sha256"),
            "hash_matches": artifact.get("hash_matches"),
            "requires_fresh_production_truth": True,
            "requires_separate_explicit_db_apply_authorization": True,
            "explicit_authorization_boundary": "future_message_and_shell_only",
            "operator_secret_boundary": "future_shell_only",
            "reads_secret_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database_in_preview": False,
            "manual_review_mode": "exception_only",
        },
        "handoff_sections": handoff_sections,
        "final_runbook_manifest": {
            "mode": "future_explicit_apply_only",
            "run_id_template": "pchome-db-apply-{utc_timestamp}-{handoff_digest}",
            "steps": final_runbook_steps,
            "step_count": len(final_runbook_steps),
            "executes_in_preview": False,
            "writes_artifact_in_preview": False,
            "writes_database": False,
        },
        "command_previews": command_previews,
        "abort_gates": abort_gates,
        "source_proof_manifest": source_proof_manifest,
        "source_artifact_preview_summary": summary,
        "safety": {
            "read_only_db_apply_final_handoff_package": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_artifact_in_preview": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this final handoff only after a separate explicit DB apply authorization is given.",
            "Refresh production truth and regenerate artifacts inside the same future apply run.",
            "Keep failures machine-routed to rollback artifacts and exception review.",
        ],
    }


def _db_apply_controlled_dry_run_shell_preview_id(final_handoff: dict[str, Any]) -> str:
    payload = {
        "policy": final_handoff.get("policy") or "",
        "result": final_handoff.get("result") or "",
        "final_handoff_package": final_handoff.get("final_handoff_package") or {},
        "summary": final_handoff.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-dry-run-shell-{digest[:16]}"


def build_pchome_auto_policy_db_apply_controlled_dry_run_shell_preview(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write shell dry-run preview for a future explicit DB apply."""
    final_handoff = build_pchome_auto_policy_db_apply_final_handoff_package(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    handoff = final_handoff.get("final_handoff_package") or {}
    source_summary = final_handoff.get("summary") or {}
    handoff_ready = bool(handoff.get("ready_for_explicit_db_apply_handoff"))
    dry_run_ready = handoff_ready and final_handoff.get("result") == "DB_APPLY_FINAL_HANDOFF_PACKAGE_READY"
    dry_run_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_PREVIEW_READY"
        if dry_run_ready
        else "WAITING_FOR_DB_APPLY_FINAL_HANDOFF_PACKAGE"
    )
    shell_preview_id = _db_apply_controlled_dry_run_shell_preview_id(final_handoff)
    shell_phases = [
        {
            "name": "initialize_dry_run_context",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "refresh_production_truth_check_mode",
            "command_preview": "python scripts/ops/check_production_version_truth.py",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "verify_final_handoff_source_chain",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-final-handoff-package",
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "verify_migration_file_hash_check_mode",
            "target_file": handoff.get("target_file"),
            "expected_sha256": handoff.get("expected_sha256"),
            "required": True,
            "executes_in_preview": False,
        },
        {
            "name": "render_artifact_paths_check_mode",
            "artifact_path_templates": [
                "artifacts/pchome_growth/db_apply_prewrite_snapshot/{run_id}.json",
                "artifacts/pchome_growth/db_apply_readback/{run_id}.json",
                "artifacts/pchome_growth/db_apply_rollback/{run_id}.json",
            ],
            "required": True,
            "writes_artifact_in_preview": False,
            "executes_in_preview": False,
        },
        {
            "name": "render_prewrite_snapshot_command_preview",
            "required": True,
            "writes_artifact_in_preview": False,
            "executes_sql_in_preview": False,
            "executes_in_preview": False,
        },
        {
            "name": "render_database_apply_command_preview",
            "command_preview": (
                'psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f '
                "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            ),
            "uses_secret_placeholder": True,
            "reads_secret_in_preview": False,
            "required": True,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
        {
            "name": "render_post_apply_verifier_command_preview",
            "required": True,
            "executes_sql_in_preview": False,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
        {
            "name": "render_abort_and_rollback_hooks",
            "required": True,
            "writes_artifact_in_preview": False,
            "executes_in_preview": False,
            "writes_database_in_preview": False,
        },
    ]
    shell_script_preview = {
        "filename": "scripts/ops/pchome_db_apply_controlled_dry_run.sh",
        "mode": "future_script_preview_only",
        "lines": [
            "#!/usr/bin/env bash",
            "set -euo pipefail",
            "DRY_RUN_ONLY=1",
            ': "${RUN_ID:=pchome-db-apply-dry-run-preview}"',
            "python scripts/ops/check_production_version_truth.py",
            "printf '%s\\n' 'DRY RUN: verify final handoff source chain and migration hash'",
            "printf '%s\\n' 'DRY RUN: would create prewrite snapshot artifact'",
            "printf '%s\\n' 'DRY RUN: would require DATABASE_URL from future shell without logging it'",
            "printf '%s\\n' 'DRY RUN: would execute psql \"$DATABASE_URL\" -v ON_ERROR_STOP=1 -f migrations/045_pchome_auto_policy_evidence_receipts.sql'",
            "printf '%s\\n' 'DRY RUN: would run post-apply verifier bundle and rollback hooks'",
        ],
        "line_count": 10,
        "writes_file_in_preview": False,
        "executes_script_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    check_mode_contract = {
        "required_checks": [
            "production_truth_passes",
            "final_handoff_package_ready",
            "migration_file_hash_matches",
            "artifact_path_templates_render",
            "database_url_not_read_in_preview",
            "all_future_write_commands_remain_preview_only",
        ],
        "required_check_count": 6,
        "dry_run_only": True,
        "executes_in_preview": False,
        "writes_database": False,
    }
    rollback_hook_preview = {
        "hooks": [
            {
                "name": "abort_before_sql_on_precheck_failure",
                "required": True,
                "executes_in_preview": False,
            },
            {
                "name": "generate_rollback_artifact_on_post_apply_failure",
                "required": True,
                "writes_artifact_in_preview": False,
                "executes_in_preview": False,
            },
            {
                "name": "route_exception_review_with_artifact_ids",
                "required": True,
                "executes_in_preview": False,
            },
        ],
        "hook_count": 3,
        "writes_artifact_in_preview": False,
        "writes_database": False,
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_SHELL_PREVIEW_POLICY,
        "result": dry_run_status,
        "success": bool(final_handoff.get("success")),
        "generated_at": final_handoff.get("generated_at"),
        "source_policy": final_handoff.get("policy"),
        "stats": final_handoff.get("stats") or {},
        "summary": {
            "dry_run_shell_preview_ready_count": 1 if dry_run_ready else 0,
            "final_handoff_ready_count": source_summary.get("final_handoff_ready_count", 0),
            "shell_phase_count": len(shell_phases),
            "shell_script_line_count": shell_script_preview["line_count"],
            "check_mode_required_check_count": check_mode_contract["required_check_count"],
            "rollback_hook_count": rollback_hook_preview["hook_count"],
            "command_preview_count": source_summary.get("command_preview_count", 0),
            "abort_gate_count": source_summary.get("abort_gate_count", 0),
            "artifact_schema_count": source_summary.get("artifact_schema_count", 0),
            "verifier_check_count": source_summary.get("verifier_check_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: source_summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "controlled_dry_run_shell_preview": {
            "preview_id": shell_preview_id,
            "source_final_handoff_package_id": handoff.get("package_id"),
            "source_artifact_preview_id": handoff.get("source_artifact_preview_id"),
            "source_authorization_package_id": handoff.get("source_authorization_package_id"),
            "source_preflight_id": handoff.get("source_preflight_id"),
            "source_request_id": handoff.get("source_request_id"),
            "status": dry_run_status,
            "ready_for_future_shell_script_generation": dry_run_ready,
            "ready_to_write_script_now": False,
            "ready_to_execute_shell_now": False,
            "ready_for_database_apply_now": False,
            "target_file": handoff.get("target_file"),
            "expected_sha256": handoff.get("expected_sha256"),
            "actual_sha256": handoff.get("actual_sha256"),
            "hash_matches": handoff.get("hash_matches"),
            "dry_run_only": True,
            "operator_secret_boundary": "future_shell_only",
            "reads_secret_in_preview": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script_in_preview": False,
            "executes_sql_in_preview": False,
            "writes_database_in_preview": False,
            "manual_review_mode": "exception_only",
        },
        "shell_phases": shell_phases,
        "shell_script_preview": shell_script_preview,
        "check_mode_contract": check_mode_contract,
        "rollback_hook_preview": rollback_hook_preview,
        "source_final_handoff_summary": source_summary,
        "safety": {
            "read_only_db_apply_controlled_dry_run_shell_preview": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preview to generate a future dry-run shell script only after separate apply authorization.",
            "Keep DATABASE_URL in the future shell boundary and out of previews, logs, and artifacts.",
            "Keep real SQL execution blocked until dry-run shell output is refreshed with production truth.",
        ],
    }


def _db_apply_controlled_dry_run_shell_closeout_id(shell_preview: dict[str, Any]) -> str:
    payload = {
        "policy": shell_preview.get("policy") or "",
        "result": shell_preview.get("result") or "",
        "controlled_dry_run_shell_preview": shell_preview.get("controlled_dry_run_shell_preview") or {},
        "summary": shell_preview.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-dry-run-closeout-{digest[:16]}"


def _db_apply_authorization_request_intake_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "explicit_authorization_boundary": closeout.get("explicit_authorization_boundary") or {},
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-intake-{digest[:16]}"


def _db_apply_authorization_request_closeout_id(intake: dict[str, Any]) -> str:
    payload = {
        "policy": intake.get("policy") or "",
        "result": intake.get("result") or "",
        "authorization_request_intake": intake.get("authorization_request_intake") or {},
        "authorization_envelope": intake.get("authorization_envelope") or {},
        "summary": intake.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-closeout-{digest[:16]}"


def _db_apply_authorization_lane_guard_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "final_exact_request_package": closeout.get("final_exact_request_package") or {},
        "machine_request_manifest": closeout.get("machine_request_manifest") or {},
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-lane-{digest[:16]}"


def _db_apply_authorization_decision_preflight_id(lane_guard: dict[str, Any]) -> str:
    payload = {
        "policy": lane_guard.get("policy") or "",
        "result": lane_guard.get("result") or "",
        "future_authorization_lane_guard": lane_guard.get("future_authorization_lane_guard") or {},
        "lane_transfer_contract": lane_guard.get("lane_transfer_contract") or {},
        "summary": lane_guard.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-decision-{digest[:16]}"


def _db_apply_authorization_decision_closeout_id(preflight: dict[str, Any]) -> str:
    payload = {
        "policy": preflight.get("policy") or "",
        "result": preflight.get("result") or "",
        "future_authorization_decision_preflight": (
            preflight.get("future_authorization_decision_preflight") or {}
        ),
        "decision_preflight_envelope": preflight.get("decision_preflight_envelope") or {},
        "summary": preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-decision-closeout-{digest[:16]}"


def _db_apply_authorization_issuer_gate_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "future_authorization_decision_package": (
            closeout.get("future_authorization_decision_package") or {}
        ),
        "decision_closeout_contract": closeout.get("decision_closeout_contract") or {},
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-issuer-gate-{digest[:16]}"


def _db_apply_authorization_signing_decision_preflight_id(issuer_gate: dict[str, Any]) -> str:
    payload = {
        "policy": issuer_gate.get("policy") or "",
        "result": issuer_gate.get("result") or "",
        "future_authorization_issuer_gate": issuer_gate.get("future_authorization_issuer_gate") or {},
        "final_nonsecret_authorization_envelope": (
            issuer_gate.get("final_nonsecret_authorization_envelope") or {}
        ),
        "issuer_gate_contract": issuer_gate.get("issuer_gate_contract") or {},
        "summary": issuer_gate.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signing-preflight-{digest[:16]}"


def _db_apply_authorization_signing_decision_closeout_id(preflight: dict[str, Any]) -> str:
    payload = {
        "policy": preflight.get("policy") or "",
        "result": preflight.get("result") or "",
        "future_authorization_signing_decision_preflight": (
            preflight.get("future_authorization_signing_decision_preflight") or {}
        ),
        "signing_decision_preflight_envelope": (
            preflight.get("signing_decision_preflight_envelope") or {}
        ),
        "summary": preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signing-closeout-{digest[:16]}"


def _db_apply_authorization_signing_issuer_guard_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "unsigned_signing_decision_package": closeout.get("unsigned_signing_decision_package") or {},
        "signing_decision_closeout_contract": (
            closeout.get("signing_decision_closeout_contract") or {}
        ),
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signing-issuer-{digest[:16]}"


def _db_apply_authorization_signing_issuer_closeout_id(guard: dict[str, Any]) -> str:
    payload = {
        "policy": guard.get("policy") or "",
        "result": guard.get("result") or "",
        "signable_request_boundary": guard.get("signable_request_boundary") or {},
        "signing_issuer_guard_contract": guard.get("signing_issuer_guard_contract") or {},
        "summary": guard.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signing-issuer-closeout-{digest[:16]}"


def _db_apply_authorization_signing_execution_preflight_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "future_authorization_signing_issuer_closeout": (
            closeout.get("future_authorization_signing_issuer_closeout") or {}
        ),
        "final_signable_request_package": closeout.get("final_signable_request_package") or {},
        "signing_issuer_closeout_contract": (
            closeout.get("signing_issuer_closeout_contract") or {}
        ),
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signing-execution-preflight-{digest[:16]}"


def _db_apply_authorization_signing_execution_closeout_id(preflight: dict[str, Any]) -> str:
    payload = {
        "policy": preflight.get("policy") or "",
        "result": preflight.get("result") or "",
        "future_authorization_signing_execution_preflight": (
            preflight.get("future_authorization_signing_execution_preflight") or {}
        ),
        "signing_execution_preflight_package": (
            preflight.get("signing_execution_preflight_package") or {}
        ),
        "operator_held_secret_boundary_contract": (
            preflight.get("operator_held_secret_boundary_contract") or {}
        ),
        "summary": preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signing-execution-closeout-{digest[:16]}"


def _db_apply_authorization_signed_receipt_preflight_id(closeout: dict[str, Any]) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "future_authorization_signing_execution_closeout": (
            closeout.get("future_authorization_signing_execution_closeout") or {}
        ),
        "unsigned_signed_authorization_receipt_boundary": (
            closeout.get("unsigned_signed_authorization_receipt_boundary") or {}
        ),
        "signing_execution_closeout_contract": (
            closeout.get("signing_execution_closeout_contract") or {}
        ),
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signed-receipt-preflight-{digest[:16]}"


def _db_apply_authorization_signed_receipt_closeout_id(preflight: dict[str, Any]) -> str:
    payload = {
        "policy": preflight.get("policy") or "",
        "result": preflight.get("result") or "",
        "future_authorization_signed_receipt_preflight": (
            preflight.get("future_authorization_signed_receipt_preflight") or {}
        ),
        "external_signing_receipt_evidence_boundary": (
            preflight.get("external_signing_receipt_evidence_boundary") or {}
        ),
        "signed_receipt_preflight_contract": (
            preflight.get("signed_receipt_preflight_contract") or {}
        ),
        "summary": preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signed-receipt-closeout-{digest[:16]}"


def _db_apply_authorization_signed_receipt_evidence_intake_id(
    closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "future_authorization_signed_receipt_closeout": (
            closeout.get("future_authorization_signed_receipt_closeout") or {}
        ),
        "detached_receipt_verification_boundary": (
            closeout.get("detached_receipt_verification_boundary") or {}
        ),
        "signed_receipt_closeout_contract": (
            closeout.get("signed_receipt_closeout_contract") or {}
        ),
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-signed-receipt-evidence-intake-{digest[:16]}"


def _db_apply_authorization_detached_verification_evidence_validation_id(
    intake: dict[str, Any],
) -> str:
    payload = {
        "policy": intake.get("policy") or "",
        "result": intake.get("result") or "",
        "future_signed_authorization_receipt_evidence_intake": (
            intake.get("future_signed_authorization_receipt_evidence_intake") or {}
        ),
        "detached_verification_evidence_schema": (
            intake.get("detached_verification_evidence_schema") or {}
        ),
        "signed_receipt_evidence_intake_contract": (
            intake.get("signed_receipt_evidence_intake_contract") or {}
        ),
        "summary": intake.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-detached-verification-evidence-validation-{digest[:16]}"


def _db_apply_authorization_verifier_receipt_closeout_id(
    validation: dict[str, Any],
) -> str:
    payload = {
        "policy": validation.get("policy") or "",
        "result": validation.get("result") or "",
        "future_detached_verification_evidence_validation": (
            validation.get("future_detached_verification_evidence_validation") or {}
        ),
        "verifier_receipt_closeout_boundary": (
            validation.get("verifier_receipt_closeout_boundary") or {}
        ),
        "detached_verification_evidence_validation_contract": (
            validation.get("detached_verification_evidence_validation_contract") or {}
        ),
        "summary": validation.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-verifier-receipt-closeout-{digest[:16]}"


def _db_apply_authorization_evidence_execution_preflight_id(
    closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "future_verifier_receipt_closeout": (
            closeout.get("future_verifier_receipt_closeout") or {}
        ),
        "verifier_receipt_evidence_handoff": (
            closeout.get("verifier_receipt_evidence_handoff") or {}
        ),
        "verifier_receipt_closeout_contract": (
            closeout.get("verifier_receipt_closeout_contract") or {}
        ),
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-evidence-execution-preflight-{digest[:16]}"


def _db_apply_authorization_evidence_execution_closeout_id(
    preflight: dict[str, Any],
) -> str:
    payload = {
        "policy": preflight.get("policy") or "",
        "result": preflight.get("result") or "",
        "future_database_apply_authorization_verifier_handoff": (
            preflight.get("future_database_apply_authorization_verifier_handoff") or {}
        ),
        "authorization_evidence_execution_preflight": (
            preflight.get("authorization_evidence_execution_preflight") or {}
        ),
        "authorization_evidence_execution_preflight_contract": (
            preflight.get("authorization_evidence_execution_preflight_contract") or {}
        ),
        "summary": preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-authorization-evidence-execution-closeout-{digest[:16]}"


def _db_apply_controlled_apply_final_preflight_id(
    closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": closeout.get("policy") or "",
        "result": closeout.get("result") or "",
        "future_database_apply_authorization_final_verifier_gate": (
            closeout.get("future_database_apply_authorization_final_verifier_gate") or {}
        ),
        "authorization_evidence_execution_closeout": (
            closeout.get("authorization_evidence_execution_closeout") or {}
        ),
        "authorization_evidence_execution_closeout_contract": (
            closeout.get("authorization_evidence_execution_closeout_contract") or {}
        ),
        "summary": closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-apply-final-preflight-{digest[:16]}"


def _db_apply_controlled_dry_run_package_id(
    final_preflight: dict[str, Any],
) -> str:
    payload = {
        "policy": final_preflight.get("policy") or "",
        "result": final_preflight.get("result") or "",
        "future_database_apply_controlled_apply_final_preflight": (
            final_preflight.get("future_database_apply_controlled_apply_final_preflight")
            or {}
        ),
        "controlled_apply_final_preflight": (
            final_preflight.get("controlled_apply_final_preflight") or {}
        ),
        "controlled_apply_final_preflight_contract": (
            final_preflight.get("controlled_apply_final_preflight_contract") or {}
        ),
        "summary": final_preflight.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-package-{digest[:16]}"


def _db_apply_controlled_dry_run_receipt_closeout_id(
    dry_run_package: dict[str, Any],
) -> str:
    payload = {
        "policy": dry_run_package.get("policy") or "",
        "result": dry_run_package.get("result") or "",
        "future_database_apply_controlled_dry_run_execution_receipt": (
            dry_run_package.get(
                "future_database_apply_controlled_dry_run_execution_receipt"
            )
            or {}
        ),
        "controlled_dry_run_package": (
            dry_run_package.get("controlled_dry_run_package") or {}
        ),
        "controlled_dry_run_package_contract": (
            dry_run_package.get("controlled_dry_run_package_contract") or {}
        ),
        "summary": dry_run_package.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-receipt-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_runner_readiness_id(
    receipt_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": receipt_closeout.get("policy") or "",
        "result": receipt_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_result_parser_verification": (
            receipt_closeout.get(
                "future_database_apply_controlled_dry_run_result_parser_verification"
            )
            or {}
        ),
        "controlled_dry_run_receipt_closeout": (
            receipt_closeout.get("controlled_dry_run_receipt_closeout") or {}
        ),
        "controlled_dry_run_receipt_closeout_contract": (
            receipt_closeout.get("controlled_dry_run_receipt_closeout_contract") or {}
        ),
        "summary": receipt_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-runner-readiness-{digest[:16]}"


def _db_apply_controlled_dry_run_execution_plan_closeout_id(
    runner_readiness: dict[str, Any],
) -> str:
    payload = {
        "policy": runner_readiness.get("policy") or "",
        "result": runner_readiness.get("result") or "",
        "future_database_apply_controlled_dry_run_execution_plan_binding": (
            runner_readiness.get(
                "future_database_apply_controlled_dry_run_execution_plan_binding"
            )
            or {}
        ),
        "controlled_dry_run_runner_readiness": (
            runner_readiness.get("controlled_dry_run_runner_readiness") or {}
        ),
        "controlled_dry_run_runner_readiness_contract": (
            runner_readiness.get("controlled_dry_run_runner_readiness_contract")
            or {}
        ),
        "summary": runner_readiness.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-execution-plan-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_command_artifact_closeout_id(
    execution_plan_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": execution_plan_closeout.get("policy") or "",
        "result": execution_plan_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_command_artifact_verification": (
            execution_plan_closeout.get(
                "future_database_apply_controlled_dry_run_command_artifact_verification"
            )
            or {}
        ),
        "controlled_dry_run_execution_plan_closeout": (
            execution_plan_closeout.get("controlled_dry_run_execution_plan_closeout")
            or {}
        ),
        "controlled_dry_run_execution_plan_closeout_contract": (
            execution_plan_closeout.get(
                "controlled_dry_run_execution_plan_closeout_contract"
            )
            or {}
        ),
        "summary": execution_plan_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-command-artifact-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_runner_execution_receipt_closeout_id(
    command_artifact_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": command_artifact_closeout.get("policy") or "",
        "result": command_artifact_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
            command_artifact_closeout.get(
                "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
            )
            or {}
        ),
        "controlled_dry_run_command_artifact_closeout": (
            command_artifact_closeout.get(
                "controlled_dry_run_command_artifact_closeout"
            )
            or {}
        ),
        "controlled_dry_run_command_artifact_closeout_contract": (
            command_artifact_closeout.get(
                "controlled_dry_run_command_artifact_closeout_contract"
            )
            or {}
        ),
        "summary": command_artifact_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-runner-execution-receipt-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_post_receipt_parser_closeout_id(
    runner_execution_receipt_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": runner_execution_receipt_closeout.get("policy") or "",
        "result": runner_execution_receipt_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_post_receipt_parser_verification": (
            runner_execution_receipt_closeout.get(
                "future_database_apply_controlled_dry_run_post_receipt_parser_verification"
            )
            or {}
        ),
        "controlled_dry_run_runner_execution_receipt_closeout": (
            runner_execution_receipt_closeout.get(
                "controlled_dry_run_runner_execution_receipt_closeout"
            )
            or {}
        ),
        "controlled_dry_run_runner_execution_receipt_closeout_contract": (
            runner_execution_receipt_closeout.get(
                "controlled_dry_run_runner_execution_receipt_closeout_contract"
            )
            or {}
        ),
        "summary": runner_execution_receipt_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-post-receipt-parser-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_no_apply_enforcement_closeout_id(
    post_receipt_parser_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": post_receipt_parser_closeout.get("policy") or "",
        "result": post_receipt_parser_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_no_apply_enforcement_verification": (
            post_receipt_parser_closeout.get(
                "future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
            )
            or {}
        ),
        "controlled_dry_run_post_receipt_parser_closeout": (
            post_receipt_parser_closeout.get(
                "controlled_dry_run_post_receipt_parser_closeout"
            )
            or {}
        ),
        "controlled_dry_run_post_receipt_parser_closeout_contract": (
            post_receipt_parser_closeout.get(
                "controlled_dry_run_post_receipt_parser_closeout_contract"
            )
            or {}
        ),
        "summary": post_receipt_parser_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-no-apply-enforcement-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_final_executor_guard_closeout_id(
    no_apply_enforcement_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": no_apply_enforcement_closeout.get("policy") or "",
        "result": no_apply_enforcement_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_final_dry_run_executor_guard": (
            no_apply_enforcement_closeout.get(
                "future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
            )
            or {}
        ),
        "controlled_dry_run_no_apply_enforcement_closeout": (
            no_apply_enforcement_closeout.get(
                "controlled_dry_run_no_apply_enforcement_closeout"
            )
            or {}
        ),
        "controlled_dry_run_no_apply_enforcement_closeout_contract": (
            no_apply_enforcement_closeout.get(
                "controlled_dry_run_no_apply_enforcement_closeout_contract"
            )
            or {}
        ),
        "summary": no_apply_enforcement_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-final-executor-guard-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_pre_apply_replay_closeout_id(
    final_executor_guard_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": final_executor_guard_closeout.get("policy") or "",
        "result": final_executor_guard_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_pre_apply_replay_verifier": (
            final_executor_guard_closeout.get(
                "future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
            )
            or {}
        ),
        "controlled_dry_run_final_executor_guard_closeout": (
            final_executor_guard_closeout.get(
                "controlled_dry_run_final_executor_guard_closeout"
            )
            or {}
        ),
        "controlled_dry_run_final_executor_guard_closeout_contract": (
            final_executor_guard_closeout.get(
                "controlled_dry_run_final_executor_guard_closeout_contract"
            )
            or {}
        ),
        "summary": final_executor_guard_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-pre-apply-replay-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_apply_executor_readiness_closeout_id(
    pre_apply_replay_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": pre_apply_replay_closeout.get("policy") or "",
        "result": pre_apply_replay_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_apply_executor_readiness_contract": (
            pre_apply_replay_closeout.get(
                "future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
            )
            or {}
        ),
        "controlled_dry_run_pre_apply_replay_closeout": (
            pre_apply_replay_closeout.get(
                "controlled_dry_run_pre_apply_replay_closeout"
            )
            or {}
        ),
        "controlled_dry_run_pre_apply_replay_closeout_contract": (
            pre_apply_replay_closeout.get(
                "controlled_dry_run_pre_apply_replay_closeout_contract"
            )
            or {}
        ),
        "summary": pre_apply_replay_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-apply-executor-readiness-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_invocation_receipt_closeout_id(
    apply_executor_readiness_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": apply_executor_readiness_closeout.get("policy") or "",
        "result": apply_executor_readiness_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_invocation_readiness_receipt": (
            apply_executor_readiness_closeout.get(
                "future_database_apply_controlled_dry_run_invocation_readiness_receipt"
            )
            or {}
        ),
        "controlled_dry_run_apply_executor_readiness_closeout": (
            apply_executor_readiness_closeout.get(
                "controlled_dry_run_apply_executor_readiness_closeout"
            )
            or {}
        ),
        "controlled_dry_run_apply_executor_readiness_closeout_contract": (
            apply_executor_readiness_closeout.get(
                "controlled_dry_run_apply_executor_readiness_closeout_contract"
            )
            or {}
        ),
        "summary": apply_executor_readiness_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-invocation-receipt-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_no_write_invocation_package_closeout_id(
    invocation_receipt_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": invocation_receipt_closeout.get("policy") or "",
        "result": invocation_receipt_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_no_write_invocation_package": (
            invocation_receipt_closeout.get(
                "future_database_apply_controlled_dry_run_no_write_invocation_package"
            )
            or {}
        ),
        "controlled_dry_run_invocation_receipt_closeout": (
            invocation_receipt_closeout.get(
                "controlled_dry_run_invocation_receipt_closeout"
            )
            or {}
        ),
        "controlled_dry_run_invocation_receipt_closeout_contract": (
            invocation_receipt_closeout.get(
                "controlled_dry_run_invocation_receipt_closeout_contract"
            )
            or {}
        ),
        "summary": invocation_receipt_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-no-write-invocation-package-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_execution_preflight_guard_closeout_id(
    no_write_invocation_package_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": no_write_invocation_package_closeout.get("policy") or "",
        "result": no_write_invocation_package_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_execution_preflight_guard": (
            no_write_invocation_package_closeout.get(
                "future_database_apply_controlled_dry_run_execution_preflight_guard"
            )
            or {}
        ),
        "controlled_dry_run_no_write_invocation_package_closeout": (
            no_write_invocation_package_closeout.get(
                "controlled_dry_run_no_write_invocation_package_closeout"
            )
            or {}
        ),
        "controlled_dry_run_no_write_invocation_package_closeout_contract": (
            no_write_invocation_package_closeout.get(
                "controlled_dry_run_no_write_invocation_package_closeout_contract"
            )
            or {}
        ),
        "summary": no_write_invocation_package_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-execution-preflight-guard-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_runner_invocation_boundary_closeout_id(
    execution_preflight_guard_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": execution_preflight_guard_closeout.get("policy") or "",
        "result": execution_preflight_guard_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_runner_invocation_boundary": (
            execution_preflight_guard_closeout.get(
                "future_database_apply_controlled_dry_run_runner_invocation_boundary"
            )
            or {}
        ),
        "controlled_dry_run_execution_preflight_guard_closeout": (
            execution_preflight_guard_closeout.get(
                "controlled_dry_run_execution_preflight_guard_closeout"
            )
            or {}
        ),
        "controlled_dry_run_execution_preflight_guard_closeout_contract": (
            execution_preflight_guard_closeout.get(
                "controlled_dry_run_execution_preflight_guard_closeout_contract"
            )
            or {}
        ),
        "summary": execution_preflight_guard_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-runner-invocation-boundary-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout_id(
    runner_invocation_boundary_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": runner_invocation_boundary_closeout.get("policy") or "",
        "result": runner_invocation_boundary_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_no_execution_receipt_handoff": (
            runner_invocation_boundary_closeout.get(
                "future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
            )
            or {}
        ),
        "controlled_dry_run_runner_invocation_boundary_closeout": (
            runner_invocation_boundary_closeout.get(
                "controlled_dry_run_runner_invocation_boundary_closeout"
            )
            or {}
        ),
        "controlled_dry_run_runner_invocation_boundary_closeout_contract": (
            runner_invocation_boundary_closeout.get(
                "controlled_dry_run_runner_invocation_boundary_closeout_contract"
            )
            or {}
        ),
        "summary": runner_invocation_boundary_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout_id(
    no_execution_receipt_handoff_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": no_execution_receipt_handoff_closeout.get("policy") or "",
        "result": no_execution_receipt_handoff_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_final_no_runner_execution_proof": (
            no_execution_receipt_handoff_closeout.get(
                "future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
            )
            or {}
        ),
        "controlled_dry_run_no_execution_receipt_handoff_closeout": (
            no_execution_receipt_handoff_closeout.get(
                "controlled_dry_run_no_execution_receipt_handoff_closeout"
            )
            or {}
        ),
        "controlled_dry_run_no_execution_receipt_handoff_closeout_contract": (
            no_execution_receipt_handoff_closeout.get(
                "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
            )
            or {}
        ),
        "summary": no_execution_receipt_handoff_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout_id(
    final_no_runner_execution_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": final_no_runner_execution_proof_closeout.get("policy") or "",
        "result": final_no_runner_execution_proof_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof": (
            final_no_runner_execution_proof_closeout.get(
                "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
            )
            or {}
        ),
        "controlled_dry_run_final_no_runner_execution_proof_closeout": (
            final_no_runner_execution_proof_closeout.get(
                "controlled_dry_run_final_no_runner_execution_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_final_no_runner_execution_proof_closeout_contract": (
            final_no_runner_execution_proof_closeout.get(
                "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
            )
            or {}
        ),
        "summary": final_no_runner_execution_proof_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-controlled-executor-quarantine-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout_id(
    controlled_executor_quarantine_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": controlled_executor_quarantine_proof_closeout.get("policy") or "",
        "result": controlled_executor_quarantine_proof_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof": (
            controlled_executor_quarantine_proof_closeout.get(
                "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
            )
            or {}
        ),
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout": (
            controlled_executor_quarantine_proof_closeout.get(
                "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract": (
            controlled_executor_quarantine_proof_closeout.get(
                "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
            )
            or {}
        ),
        "summary": controlled_executor_quarantine_proof_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-execution-envelope-freeze-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_id(
    execution_envelope_freeze_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": execution_envelope_freeze_proof_closeout.get("policy") or "",
        "result": execution_envelope_freeze_proof_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff": (
            execution_envelope_freeze_proof_closeout.get(
                "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
            )
            or {}
        ),
        "controlled_dry_run_execution_envelope_freeze_proof_closeout": (
            execution_envelope_freeze_proof_closeout.get(
                "controlled_dry_run_execution_envelope_freeze_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract": (
            execution_envelope_freeze_proof_closeout.get(
                "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
            )
            or {}
        ),
        "summary": execution_envelope_freeze_proof_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-frozen-envelope-verifier-handoff-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout_id(
    frozen_envelope_verifier_handoff_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": frozen_envelope_verifier_handoff_closeout.get("policy") or "",
        "result": frozen_envelope_verifier_handoff_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
            frozen_envelope_verifier_handoff_closeout.get(
                "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
            )
            or {}
        ),
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout": (
            frozen_envelope_verifier_handoff_closeout.get(
                "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
            )
            or {}
        ),
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract": (
            frozen_envelope_verifier_handoff_closeout.get(
                "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
            )
            or {}
        ),
        "summary": frozen_envelope_verifier_handoff_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-verifier-invocation-lock-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_id(
    verifier_invocation_lock_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": verifier_invocation_lock_proof_closeout.get("policy") or "",
        "result": verifier_invocation_lock_proof_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof": (
            verifier_invocation_lock_proof_closeout.get(
                "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
            )
            or {}
        ),
        "controlled_dry_run_verifier_invocation_lock_proof_closeout": (
            verifier_invocation_lock_proof_closeout.get(
                "controlled_dry_run_verifier_invocation_lock_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract": (
            verifier_invocation_lock_proof_closeout.get(
                "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract"
            )
            or {}
        ),
        "summary": verifier_invocation_lock_proof_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-verifier-no-execution-receipt-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_id(
    verifier_no_execution_receipt_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": verifier_no_execution_receipt_proof_closeout.get("policy") or "",
        "result": verifier_no_execution_receipt_proof_closeout.get("result") or "",
        "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof": (
            verifier_no_execution_receipt_proof_closeout.get(
                "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
            )
            or {}
        ),
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout": (
            verifier_no_execution_receipt_proof_closeout.get(
                "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract": (
            verifier_no_execution_receipt_proof_closeout.get(
                "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract"
            )
            or {}
        ),
        "summary": verifier_no_execution_receipt_proof_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-verifier-receipt-persistence-guard-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_id(
    verifier_receipt_persistence_guard_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": verifier_receipt_persistence_guard_proof_closeout.get("policy")
        or "",
        "result": verifier_receipt_persistence_guard_proof_closeout.get("result")
        or "",
        "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof": (
            verifier_receipt_persistence_guard_proof_closeout.get(
                "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
            )
            or {}
        ),
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout": (
            verifier_receipt_persistence_guard_proof_closeout.get(
                "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract": (
            verifier_receipt_persistence_guard_proof_closeout.get(
                "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract"
            )
            or {}
        ),
        "summary": verifier_receipt_persistence_guard_proof_closeout.get(
            "summary"
        )
        or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-receipt-persistence-storage-boundary-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_id(
    receipt_persistence_storage_boundary_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": receipt_persistence_storage_boundary_proof_closeout.get("policy")
        or "",
        "result": receipt_persistence_storage_boundary_proof_closeout.get("result")
        or "",
        "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof": (
            receipt_persistence_storage_boundary_proof_closeout.get(
                "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
            )
            or {}
        ),
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout": (
            receipt_persistence_storage_boundary_proof_closeout.get(
                "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract": (
            receipt_persistence_storage_boundary_proof_closeout.get(
                "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract"
            )
            or {}
        ),
        "summary": receipt_persistence_storage_boundary_proof_closeout.get(
            "summary"
        )
        or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-storage-boundary-no-write-ledger-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout_id(
    storage_boundary_no_write_ledger_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": storage_boundary_no_write_ledger_proof_closeout.get("policy")
        or "",
        "result": storage_boundary_no_write_ledger_proof_closeout.get("result")
        or "",
        "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof": (
            storage_boundary_no_write_ledger_proof_closeout.get(
                "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
            )
            or {}
        ),
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout": (
            storage_boundary_no_write_ledger_proof_closeout.get(
                "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract": (
            storage_boundary_no_write_ledger_proof_closeout.get(
                "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract"
            )
            or {}
        ),
        "summary": storage_boundary_no_write_ledger_proof_closeout.get(
            "summary"
        )
        or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-no-write-ledger-retention-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_id(
    no_write_ledger_retention_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": no_write_ledger_retention_proof_closeout.get("policy")
        or "",
        "result": no_write_ledger_retention_proof_closeout.get("result")
        or "",
        "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof": (
            no_write_ledger_retention_proof_closeout.get(
                "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
            )
            or {}
        ),
        "controlled_dry_run_no_write_ledger_retention_proof_closeout": (
            no_write_ledger_retention_proof_closeout.get(
                "controlled_dry_run_no_write_ledger_retention_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract": (
            no_write_ledger_retention_proof_closeout.get(
                "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract"
            )
            or {}
        ),
        "summary": no_write_ledger_retention_proof_closeout.get("summary") or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-retention-boundary-no-write-archive-proof-closeout-{digest[:16]}"


def _db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_id(
    retention_boundary_no_write_archive_proof_closeout: dict[str, Any],
) -> str:
    payload = {
        "policy": retention_boundary_no_write_archive_proof_closeout.get("policy")
        or "",
        "result": retention_boundary_no_write_archive_proof_closeout.get("result")
        or "",
        "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof": (
            retention_boundary_no_write_archive_proof_closeout.get(
                "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
            )
            or {}
        ),
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout": (
            retention_boundary_no_write_archive_proof_closeout.get(
                "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
            )
            or {}
        ),
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract": (
            retention_boundary_no_write_archive_proof_closeout.get(
                "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract"
            )
            or {}
        ),
        "summary": retention_boundary_no_write_archive_proof_closeout.get(
            "summary"
        )
        or {},
    }
    digest = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
    return f"pchome-db-apply-controlled-dry-run-archive-retention-sealed-handoff-proof-closeout-{digest[:16]}"


def _dry_run_closeout_check(key: str, passed: bool, evidence: Any, failure_route: str) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_request_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_lane_guard_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_decision_preflight_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_decision_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_issuer_gate_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signing_decision_preflight_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signing_decision_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signing_issuer_guard_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signing_issuer_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signing_execution_preflight_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signing_execution_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signed_receipt_preflight_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signed_receipt_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_signed_receipt_evidence_intake_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_detached_verification_evidence_validation_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_verifier_receipt_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_evidence_execution_preflight_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _authorization_evidence_execution_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_apply_final_preflight_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_package_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_receipt_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_runner_readiness_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_execution_plan_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_command_artifact_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_runner_execution_receipt_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_post_receipt_parser_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_no_apply_enforcement_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_final_executor_guard_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_pre_apply_replay_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_apply_executor_readiness_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_invocation_receipt_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_no_write_invocation_package_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_execution_preflight_guard_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_runner_invocation_boundary_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
    key: str,
    passed: bool,
    evidence: Any,
    failure_route: str,
) -> dict[str, Any]:
    return {
        "key": key,
        "status": "pass" if passed else "waiting",
        "passed": bool(passed),
        "evidence": evidence,
        "failure_route": failure_route,
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_shell_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the controlled dry-run shell preview without executing it."""
    shell_preview = build_pchome_auto_policy_db_apply_controlled_dry_run_shell_preview(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    shell = shell_preview.get("controlled_dry_run_shell_preview") or {}
    summary = shell_preview.get("summary") or {}
    shell_script = shell_preview.get("shell_script_preview") or {}
    check_mode = shell_preview.get("check_mode_contract") or {}
    rollback_hooks = shell_preview.get("rollback_hook_preview") or {}
    safety = shell_preview.get("safety") or {}
    checks = [
        _dry_run_closeout_check(
            "production_truth_required",
            True,
            "production /health must be refreshed immediately before any future explicit DB apply",
            "abort_before_authorization_boundary",
        ),
        _dry_run_closeout_check(
            "controlled_dry_run_shell_preview_ready",
            shell_preview.get("result") == "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_PREVIEW_READY"
            and bool(shell.get("ready_for_future_shell_script_generation")),
            {
                "result": shell_preview.get("result"),
                "ready_for_future_shell_script_generation": shell.get(
                    "ready_for_future_shell_script_generation"
                ),
            },
            "wait_for_controlled_dry_run_shell_preview",
        ),
        _dry_run_closeout_check(
            "final_handoff_ready",
            int(summary.get("final_handoff_ready_count") or 0) == 1,
            {"final_handoff_ready_count": summary.get("final_handoff_ready_count", 0)},
            "wait_for_final_handoff_package",
        ),
        _dry_run_closeout_check(
            "shell_phase_contract_complete",
            int(summary.get("shell_phase_count") or 0) >= 9,
            {"shell_phase_count": summary.get("shell_phase_count", 0)},
            "wait_for_shell_phase_contract",
        ),
        _dry_run_closeout_check(
            "shell_script_preview_complete",
            int(summary.get("shell_script_line_count") or 0) >= 10
            and shell_script.get("writes_file_in_preview") is False
            and shell_script.get("executes_script_in_preview") is False,
            {
                "shell_script_line_count": summary.get("shell_script_line_count", 0),
                "writes_file_in_preview": shell_script.get("writes_file_in_preview"),
                "executes_script_in_preview": shell_script.get("executes_script_in_preview"),
            },
            "wait_for_shell_script_preview",
        ),
        _dry_run_closeout_check(
            "check_mode_contract_complete",
            int(check_mode.get("required_check_count") or 0) >= 6
            and check_mode.get("dry_run_only") is True,
            {
                "required_check_count": check_mode.get("required_check_count", 0),
                "dry_run_only": check_mode.get("dry_run_only"),
            },
            "wait_for_check_mode_contract",
        ),
        _dry_run_closeout_check(
            "rollback_hooks_complete",
            int(rollback_hooks.get("hook_count") or 0) >= 3,
            {"rollback_hook_count": rollback_hooks.get("hook_count", 0)},
            "wait_for_rollback_hooks",
        ),
        _dry_run_closeout_check(
            "preview_writes_no_script",
            int(summary.get("writes_script_count") or 0) == 0
            and shell.get("ready_to_write_script_now") is False
            and safety.get("writes_script_in_preview") is False,
            {
                "writes_script_count": summary.get("writes_script_count", 0),
                "ready_to_write_script_now": shell.get("ready_to_write_script_now"),
                "safety_writes_script_in_preview": safety.get("writes_script_in_preview"),
            },
            "block_until_no_script_write_preview",
        ),
        _dry_run_closeout_check(
            "preview_executes_no_shell",
            int(summary.get("executes_script_count") or 0) == 0
            and shell.get("ready_to_execute_shell_now") is False
            and safety.get("executes_script") is False,
            {
                "executes_script_count": summary.get("executes_script_count", 0),
                "ready_to_execute_shell_now": shell.get("ready_to_execute_shell_now"),
                "safety_executes_script": safety.get("executes_script"),
            },
            "block_until_no_shell_execution_preview",
        ),
        _dry_run_closeout_check(
            "preview_reads_no_secret",
            int(summary.get("reads_secret_count") or 0) == 0
            and shell.get("reads_secret_in_preview") is False
            and safety.get("reads_secret_in_preview") is False,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "shell_reads_secret_in_preview": shell.get("reads_secret_in_preview"),
                "safety_reads_secret_in_preview": safety.get("reads_secret_in_preview"),
            },
            "block_until_secret_boundary_clean",
        ),
        _dry_run_closeout_check(
            "preview_executes_no_sql",
            int(summary.get("executes_sql_count") or 0) == 0
            and shell.get("executes_sql_in_preview") is False
            and safety.get("executes_sql") is False,
            {
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "shell_executes_sql_in_preview": shell.get("executes_sql_in_preview"),
                "safety_executes_sql": safety.get("executes_sql"),
            },
            "block_until_no_sql_preview",
        ),
        _dry_run_closeout_check(
            "preview_writes_no_database",
            int(summary.get("writes_database_count") or 0) == 0
            and shell.get("writes_database_in_preview") is False
            and safety.get("writes_database") is False,
            {
                "writes_database_count": summary.get("writes_database_count", 0),
                "shell_writes_database_in_preview": shell.get("writes_database_in_preview"),
                "safety_writes_database": safety.get("writes_database"),
            },
            "block_until_no_db_write_preview",
        ),
        _dry_run_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0,
            {LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0)},
            "route_only_failed_verifiers_to_exception_review",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_CONTROLLED_DRY_RUN_SHELL_PREVIEW"
    )
    explicit_authorization_boundary = {
        "boundary_id": _db_apply_controlled_dry_run_shell_closeout_id(shell_preview),
        "source_dry_run_shell_preview_id": shell.get("preview_id"),
        "source_final_handoff_package_id": shell.get("source_final_handoff_package_id"),
        "source_artifact_preview_id": shell.get("source_artifact_preview_id"),
        "source_authorization_package_id": shell.get("source_authorization_package_id"),
        "source_preflight_id": shell.get("source_preflight_id"),
        "source_request_id": shell.get("source_request_id"),
        "status": closeout_status,
        "ready_for_explicit_apply_authorization_boundary": closeout_ready,
        "ready_for_database_apply_now": False,
        "target_file": shell.get("target_file"),
        "expected_sha256": shell.get("expected_sha256"),
        "actual_sha256": shell.get("actual_sha256"),
        "hash_matches": shell.get("hash_matches"),
        "requires_new_explicit_db_apply_authorization": True,
        "requires_fresh_production_truth_in_future_run": True,
        "requires_future_shell_secret_injection": True,
        "operator_secret_boundary": "future_shell_only",
        "reads_secret_in_preview": False,
        "writes_script_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    future_apply_boundaries = [
        {
            "key": "fresh_production_truth_same_run",
            "required": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "fresh_final_handoff_and_dry_run_closeout",
            "required": True,
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-shell-closeout",
        },
        {
            "key": "database_url_from_future_shell_only",
            "required": True,
            "reads_secret_in_preview": False,
        },
        {
            "key": "prewrite_snapshot_before_sql",
            "required": True,
            "writes_artifact_in_preview": False,
        },
        {
            "key": "post_apply_verifier_after_sql",
            "required": True,
            "executes_sql_in_preview": False,
        },
        {
            "key": "rollback_artifact_on_verifier_failure",
            "required": True,
            "writes_artifact_in_preview": False,
        },
    ]

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(shell_preview.get("success")),
        "generated_at": shell_preview.get("generated_at"),
        "source_policy": shell_preview.get("policy"),
        "stats": shell_preview.get("stats") or {},
        "summary": {
            "closeout_ready_count": 1 if closeout_ready else 0,
            "closeout_check_count": len(checks),
            "closeout_pass_count": passed_count,
            "closeout_waiting_count": len(waiting_checks),
            "dry_run_shell_preview_ready_count": summary.get("dry_run_shell_preview_ready_count", 0),
            "future_apply_boundary_count": len(future_apply_boundaries),
            "shell_phase_count": summary.get("shell_phase_count", 0),
            "shell_script_line_count": summary.get("shell_script_line_count", 0),
            "check_mode_required_check_count": summary.get("check_mode_required_check_count", 0),
            "rollback_hook_count": summary.get("rollback_hook_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "controlled_dry_run_shell_closeout": {
            "status": closeout_status,
            "ready_for_explicit_apply_authorization_boundary": closeout_ready,
            "ready_for_database_apply_now": False,
            "waiting_checks": waiting_checks,
            "manual_review_mode": "exception_only",
        },
        "explicit_authorization_boundary": explicit_authorization_boundary,
        "future_apply_boundaries": future_apply_boundaries,
        "closeout_checks": checks,
        "source_dry_run_shell_summary": summary,
        "safety": {
            "read_only_db_apply_controlled_dry_run_shell_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Treat this closeout as the final no-write boundary before any separate explicit DB apply authorization.",
            "Do not execute shell, SQL, or DB writes from this preview.",
            "Refresh production truth, dry-run closeout, and artifacts inside the future apply run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_decision_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Prepare no-write inputs for a future DB apply authorization decision."""
    lane_guard = build_pchome_auto_policy_db_apply_authorization_lane_guard(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    lane = lane_guard.get("future_authorization_lane_guard") or {}
    contract = lane_guard.get("lane_transfer_contract") or {}
    summary = lane_guard.get("summary") or {}
    source_package = lane_guard.get("source_final_exact_request_package") or {}
    source_manifest = lane_guard.get("source_machine_request_manifest") or {}
    source_manifest_steps = source_manifest.get("manifest_steps") or []
    lane_requirements = lane_guard.get("lane_entry_requirements") or []
    requirement_keys = {item.get("key") for item in lane_requirements}
    side_effect_free = (
        int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and lane.get("reads_secret_in_preview") is False
        and lane.get("executes_shell_in_preview") is False
        and lane.get("executes_sql_in_preview") is False
        and lane.get("writes_database_in_preview") is False
    )
    decision_input_requirements = [
        {
            "key": "fresh_production_truth_same_run",
            "required": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "authorization_lane_guard_id",
            "required": True,
            "source_id": lane.get("guard_id"),
        },
        {
            "key": "final_exact_request_package_id",
            "required": True,
            "source_id": lane.get("source_closeout_package_id"),
        },
        {
            "key": "exact_request_payload",
            "required": True,
            "field_count": summary.get("exact_request_payload_field_count", 0),
        },
        {
            "key": "migration_target_hash",
            "required": True,
            "target_file": lane.get("target_file"),
            "expected_sha256": lane.get("expected_sha256"),
            "hash_matches": lane.get("hash_matches"),
        },
        {
            "key": "secret_boundary_rejection_proof",
            "required": True,
            "operator_secret_boundary": lane.get("operator_secret_boundary"),
            "reads_secret_in_preview": False,
        },
        {
            "key": "rollback_boundary_acknowledgement",
            "required": True,
        },
        {
            "key": "post_apply_verifier_reference",
            "required": True,
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview",
        },
    ]
    decision_rejection_policy = [
        "production_truth_missing_or_stale",
        "authorization_lane_guard_not_ready",
        "exact_request_payload_missing_or_mutated",
        "migration_hash_missing_or_mismatch",
        "secret_material_present_in_request",
        "rollback_boundary_missing",
        "post_apply_verifier_missing",
        "direct_database_apply_requested_from_decision_preflight",
        "preview_attempted_shell_sql_or_database_side_effect",
        "manual_review_batch_regression_detected",
    ]
    checks = [
        _authorization_decision_preflight_check(
            "authorization_lane_guard_ready",
            lane_guard.get("result") == "DB_APPLY_AUTHORIZATION_LANE_GUARD_READY"
            and lane.get("ready_for_future_authorization_lane_entry") is True,
            {
                "result": lane_guard.get("result"),
                "ready_for_future_authorization_lane_entry": lane.get(
                    "ready_for_future_authorization_lane_entry"
                ),
            },
            "wait_for_authorization_lane_guard",
        ),
        _authorization_decision_preflight_check(
            "lane_contract_is_no_authorization",
            contract.get("issues_database_apply_authorization") is False
            and contract.get("ready_for_database_apply_now") is False
            and contract.get("writes_database") is False,
            {
                "issues_database_apply_authorization": contract.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": contract.get("ready_for_database_apply_now"),
                "writes_database": contract.get("writes_database"),
            },
            "block_if_lane_contract_authorizes_apply",
        ),
        _authorization_decision_preflight_check(
            "same_run_production_truth_required",
            "production_truth_refreshed_in_same_run" in requirement_keys
            and lane.get("requires_fresh_production_truth_in_same_run") is True,
            {
                "requirement_keys": sorted(key for key in requirement_keys if key),
                "requires_fresh_production_truth_in_same_run": lane.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
            },
            "require_same_run_production_truth",
        ),
        _authorization_decision_preflight_check(
            "decision_inputs_complete",
            len(decision_input_requirements) == 8
            and all(item.get("required") is True for item in decision_input_requirements),
            {"decision_input_requirement_count": len(decision_input_requirements)},
            "wait_for_decision_input_requirements",
        ),
        _authorization_decision_preflight_check(
            "exact_request_payload_complete",
            int(summary.get("exact_request_payload_field_count") or 0) == 10
            and source_package.get("payload_template_field_count") == 10,
            {
                "exact_request_payload_field_count": summary.get(
                    "exact_request_payload_field_count", 0
                ),
                "payload_template_field_count": source_package.get("payload_template_field_count"),
            },
            "wait_for_exact_request_payload",
        ),
        _authorization_decision_preflight_check(
            "migration_target_hash_locked",
            bool(lane.get("target_file"))
            and bool(lane.get("expected_sha256"))
            and lane.get("hash_matches") is True,
            {"target_file": lane.get("target_file"), "hash_matches": lane.get("hash_matches")},
            "abort_on_migration_hash_gap",
        ),
        _authorization_decision_preflight_check(
            "secret_boundary_rejects_secret_material",
            "secret_material_absent_from_request" in requirement_keys
            and lane.get("operator_secret_boundary") == "future_shell_only"
            and lane.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": lane.get("operator_secret_boundary"),
                "reads_secret_in_preview": lane.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_decision_preflight_check(
            "rollback_boundary_required",
            "rollback_boundary_acknowledged" in requirement_keys,
            {"requirement_keys": sorted(key for key in requirement_keys if key)},
            "block_until_rollback_boundary_is_present",
        ),
        _authorization_decision_preflight_check(
            "source_manifest_complete",
            source_manifest.get("manifest_step_count") == 6
            and len(source_manifest_steps) == 6,
            {
                "manifest_step_count": source_manifest.get("manifest_step_count"),
                "manifest_step_len": len(source_manifest_steps),
            },
            "wait_for_machine_request_manifest",
        ),
        _authorization_decision_preflight_check(
            "rejection_policy_complete",
            len(decision_rejection_policy) == 10
            and "direct_database_apply_requested_from_decision_preflight" in decision_rejection_policy,
            {"decision_rejection_reason_count": len(decision_rejection_policy)},
            "wait_for_decision_rejection_policy",
        ),
        _authorization_decision_preflight_check(
            "preview_has_no_side_effects",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
            },
            "abort_on_preview_side_effect",
        ),
        _authorization_decision_preflight_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0,
            {LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0)},
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    preflight_ready = not waiting_checks
    preflight_status = (
        "DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_LANE_GUARD"
    )
    future_authorization_decision_preflight = {
        "preflight_id": _db_apply_authorization_decision_preflight_id(lane_guard),
        "source_lane_guard_id": lane.get("guard_id"),
        "source_closeout_package_id": lane.get("source_closeout_package_id"),
        "source_intake_id": lane.get("source_intake_id"),
        "source_closeout_boundary_id": lane.get("source_closeout_boundary_id"),
        "status": preflight_status,
        "ready_for_future_authorization_decision": preflight_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "can_enter_authorization_decision_lane": preflight_ready,
        "request_scope": "future_explicit_db_apply_authorization_only",
        "target_file": lane.get("target_file"),
        "expected_sha256": lane.get("expected_sha256"),
        "actual_sha256": lane.get("actual_sha256"),
        "hash_matches": lane.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "operator_secret_boundary": "future_shell_only",
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    decision_preflight_envelope = {
        "mode": "authorization_decision_preflight_only",
        "allows_authorization_decision_in_future_lane": preflight_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "rejects_direct_database_apply": True,
        "requires_post_apply_verifier": True,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_POLICY,
        "result": preflight_status,
        "success": bool(lane_guard.get("success")),
        "generated_at": lane_guard.get("generated_at"),
        "source_policy": lane_guard.get("policy"),
        "stats": lane_guard.get("stats") or {},
        "summary": {
            "authorization_decision_preflight_ready_count": 1 if preflight_ready else 0,
            "decision_preflight_check_count": len(checks),
            "decision_preflight_pass_count": passed_count,
            "decision_preflight_waiting_count": len(waiting_checks),
            "authorization_lane_guard_ready_count": summary.get(
                "authorization_lane_guard_ready_count", 0
            ),
            "decision_input_requirement_count": len(decision_input_requirements),
            "decision_rejection_reason_count": len(decision_rejection_policy),
            "lane_entry_requirement_count": summary.get("lane_entry_requirement_count", 0),
            "exact_request_payload_field_count": summary.get(
                "exact_request_payload_field_count", 0
            ),
            "machine_request_manifest_step_count": summary.get(
                "machine_request_manifest_step_count", 0
            ),
            "required_request_evidence_count": summary.get("required_request_evidence_count", 0),
            "authorization_acceptance_gate_count": summary.get(
                "authorization_acceptance_gate_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_decision_preflight": future_authorization_decision_preflight,
        "decision_preflight_envelope": decision_preflight_envelope,
        "decision_input_requirements": decision_input_requirements,
        "decision_rejection_policy": decision_rejection_policy,
        "decision_preflight_checks": checks,
        "source_lane_guard_summary": summary,
        "source_lane_transfer_contract": contract,
        "source_final_exact_request_package": source_package,
        "safety": {
            "read_only_db_apply_authorization_decision_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preflight to verify inputs before a future authorization decision lane.",
            "Keep actual DB apply authorization out of this preflight.",
            "Require same-run production truth, secret rejection, rollback boundary, and post-apply verifier before any future decision.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_decision_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the no-write package for a future authorization decision lane."""
    preflight = build_pchome_auto_policy_db_apply_authorization_decision_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    decision = preflight.get("future_authorization_decision_preflight") or {}
    envelope = preflight.get("decision_preflight_envelope") or {}
    summary = preflight.get("summary") or {}
    decision_input_requirements = preflight.get("decision_input_requirements") or []
    decision_rejection_policy = preflight.get("decision_rejection_policy") or []
    input_keys = {item.get("key") for item in decision_input_requirements}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and decision.get("reads_secret_in_preview") is False
        and decision.get("executes_shell_in_preview") is False
        and decision.get("executes_sql_in_preview") is False
        and decision.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_decision_closeout_check(
            "authorization_decision_preflight_ready",
            preflight.get("result") == "DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_READY"
            and decision.get("ready_for_future_authorization_decision") is True,
            {
                "result": preflight.get("result"),
                "ready_for_future_authorization_decision": decision.get(
                    "ready_for_future_authorization_decision"
                ),
            },
            "wait_for_authorization_decision_preflight",
        ),
        _authorization_decision_closeout_check(
            "decision_envelope_allows_future_lane_only",
            envelope.get("allows_authorization_decision_in_future_lane") is True
            and envelope.get("issues_database_apply_authorization") is False
            and envelope.get("ready_for_database_apply_now") is False,
            {
                "allows_authorization_decision_in_future_lane": envelope.get(
                    "allows_authorization_decision_in_future_lane"
                ),
                "issues_database_apply_authorization": envelope.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": envelope.get("ready_for_database_apply_now"),
            },
            "block_if_decision_envelope_authorizes_apply",
        ),
        _authorization_decision_closeout_check(
            "decision_inputs_complete",
            len(decision_input_requirements) == 8
            and all(item.get("required") is True for item in decision_input_requirements),
            {
                "decision_input_requirement_count": len(decision_input_requirements),
                "input_keys": sorted(key for key in input_keys if key),
            },
            "wait_for_decision_input_requirements",
        ),
        _authorization_decision_closeout_check(
            "decision_rejection_policy_complete",
            len(decision_rejection_policy) == 10
            and "direct_database_apply_requested_from_decision_preflight"
            in decision_rejection_policy,
            {"decision_rejection_reason_count": len(decision_rejection_policy)},
            "wait_for_decision_rejection_policy",
        ),
        _authorization_decision_closeout_check(
            "same_run_production_truth_required",
            "fresh_production_truth_same_run" in input_keys
            and decision.get("requires_fresh_production_truth_in_same_run") is True,
            {
                "input_keys": sorted(key for key in input_keys if key),
                "requires_fresh_production_truth_in_same_run": decision.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
            },
            "require_same_run_production_truth",
        ),
        _authorization_decision_closeout_check(
            "post_apply_verifier_required",
            "post_apply_verifier_reference" in input_keys
            and envelope.get("requires_post_apply_verifier") is True,
            {
                "input_keys": sorted(key for key in input_keys if key),
                "requires_post_apply_verifier": envelope.get("requires_post_apply_verifier"),
            },
            "require_post_apply_verifier_artifact",
        ),
        _authorization_decision_closeout_check(
            "migration_target_hash_locked",
            bool(decision.get("target_file"))
            and bool(decision.get("expected_sha256"))
            and decision.get("hash_matches") is True,
            {
                "target_file": decision.get("target_file"),
                "hash_matches": decision.get("hash_matches"),
            },
            "abort_on_migration_hash_gap",
        ),
        _authorization_decision_closeout_check(
            "secret_boundary_clean",
            "secret_boundary_rejection_proof" in input_keys
            and decision.get("operator_secret_boundary") == "future_shell_only"
            and decision.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": decision.get("operator_secret_boundary"),
                "reads_secret_in_preview": decision.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_decision_closeout_check(
            "source_lane_guard_and_package_ids_present",
            bool(decision.get("preflight_id"))
            and bool(decision.get("source_lane_guard_id"))
            and bool(decision.get("source_closeout_package_id"))
            and bool(decision.get("source_intake_id"))
            and bool(decision.get("source_closeout_boundary_id")),
            {
                "preflight_id": decision.get("preflight_id"),
                "source_lane_guard_id": decision.get("source_lane_guard_id"),
                "source_closeout_package_id": decision.get("source_closeout_package_id"),
                "source_intake_id": decision.get("source_intake_id"),
                "source_closeout_boundary_id": decision.get("source_closeout_boundary_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_decision_closeout_check(
            "preview_has_no_side_effects",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
            },
            "abort_on_preview_side_effect",
        ),
        _authorization_decision_closeout_check(
            "direct_apply_still_rejected",
            envelope.get("rejects_direct_database_apply") is True
            and decision.get("issues_database_apply_authorization") is False
            and decision.get("ready_for_database_apply_now") is False,
            {
                "rejects_direct_database_apply": envelope.get("rejects_direct_database_apply"),
                "issues_database_apply_authorization": decision.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": decision.get("ready_for_database_apply_now"),
            },
            "reject_direct_database_apply_from_closeout",
        ),
        _authorization_decision_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and decision.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": decision.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT"
    )
    future_authorization_decision_closeout = {
        "closeout_id": _db_apply_authorization_decision_closeout_id(preflight),
        "source_preflight_id": decision.get("preflight_id"),
        "source_lane_guard_id": decision.get("source_lane_guard_id"),
        "source_closeout_package_id": decision.get("source_closeout_package_id"),
        "source_intake_id": decision.get("source_intake_id"),
        "source_closeout_boundary_id": decision.get("source_closeout_boundary_id"),
        "status": closeout_status,
        "ready_for_future_authorization_decision_closeout": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    future_authorization_decision_package = {
        "package_id": future_authorization_decision_closeout["closeout_id"],
        "source_preflight_id": decision.get("preflight_id"),
        "source_lane_guard_id": decision.get("source_lane_guard_id"),
        "source_closeout_package_id": decision.get("source_closeout_package_id"),
        "source_intake_id": decision.get("source_intake_id"),
        "source_closeout_boundary_id": decision.get("source_closeout_boundary_id"),
        "status": closeout_status,
        "ready_for_future_authorization_decision_package": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "decision_scope": "future_explicit_db_apply_authorization_decision_only",
        "target_file": decision.get("target_file"),
        "expected_sha256": decision.get("expected_sha256"),
        "actual_sha256": decision.get("actual_sha256"),
        "hash_matches": decision.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview"
        ),
        "operator_secret_boundary": "future_shell_only",
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    decision_closeout_contract = {
        "mode": "future_authorization_decision_closeout_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-closeout"
        ),
        "source_preflight_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-preflight"
        ),
        "machine_verifiable": True,
        "permits_future_authorization_decision_lane": closeout_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "writes_database": False,
        "executes_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(preflight.get("success")),
        "generated_at": preflight.get("generated_at"),
        "source_policy": preflight.get("policy"),
        "stats": preflight.get("stats") or {},
        "summary": {
            "authorization_decision_closeout_ready_count": 1 if closeout_ready else 0,
            "decision_closeout_check_count": len(checks),
            "decision_closeout_pass_count": passed_count,
            "decision_closeout_waiting_count": len(waiting_checks),
            "authorization_decision_preflight_ready_count": summary.get(
                "authorization_decision_preflight_ready_count", 0
            ),
            "decision_input_requirement_count": len(decision_input_requirements),
            "decision_rejection_reason_count": len(decision_rejection_policy),
            "post_apply_verifier_required_count": (
                1 if envelope.get("requires_post_apply_verifier") is True else 0
            ),
            "same_run_truth_required_count": (
                1 if decision.get("requires_fresh_production_truth_in_same_run") is True else 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_decision_closeout": future_authorization_decision_closeout,
        "future_authorization_decision_package": future_authorization_decision_package,
        "decision_closeout_contract": decision_closeout_contract,
        "decision_closeout_checks": checks,
        "source_decision_preflight_summary": summary,
        "source_decision_input_requirements": decision_input_requirements,
        "source_decision_rejection_policy": decision_rejection_policy,
        "safety": {
            "read_only_db_apply_authorization_decision_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the machine-readable package for a future explicit authorization decision lane.",
            "Keep database apply authorization and SQL execution out of this closeout.",
            "Require fresh production truth, secret rejection, rollback boundary, and post-apply verifier inside the future decision run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_issuer_gate(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-secret issuer gate envelope without signing DB apply authorization."""
    closeout = build_pchome_auto_policy_db_apply_authorization_decision_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    decision = closeout.get("future_authorization_decision_closeout") or {}
    package = closeout.get("future_authorization_decision_package") or {}
    contract = closeout.get("decision_closeout_contract") or {}
    summary = closeout.get("summary") or {}
    rejection_policy = closeout.get("source_decision_rejection_policy") or []
    source_inputs = closeout.get("source_decision_input_requirements") or []
    source_input_keys = {item.get("key") for item in source_inputs}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and package.get("reads_secret_in_preview") is False
        and package.get("executes_shell_in_preview") is False
        and package.get("executes_sql_in_preview") is False
        and package.get("writes_database_in_preview") is False
    )
    required_issuer_evidence = [
        {
            "key": "fresh_production_truth_same_run",
            "required": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "decision_closeout_id",
            "required": True,
            "source_id": decision.get("closeout_id"),
        },
        {
            "key": "decision_preflight_id",
            "required": True,
            "source_id": package.get("source_preflight_id"),
        },
        {
            "key": "authorization_lane_guard_id",
            "required": True,
            "source_id": package.get("source_lane_guard_id"),
        },
        {
            "key": "final_request_package_id",
            "required": True,
            "source_id": package.get("source_closeout_package_id"),
        },
        {
            "key": "migration_target_hash",
            "required": True,
            "target_file": package.get("target_file"),
            "expected_sha256": package.get("expected_sha256"),
            "hash_matches": package.get("hash_matches"),
        },
        {
            "key": "secret_boundary_rejection",
            "required": True,
            "operator_secret_boundary": package.get("operator_secret_boundary"),
            "secret_material_included": False,
        },
        {
            "key": "post_apply_verifier_reference",
            "required": True,
            "source_endpoint": package.get("post_apply_verifier_endpoint"),
        },
        {
            "key": "direct_apply_rejection_policy",
            "required": True,
            "source_rejection": "direct_database_apply_requested_from_decision_preflight",
        },
    ]
    nonsecret_authorization_claims = [
        {
            "key": "source_decision_closeout_ready",
            "claim": decision.get("ready_for_future_authorization_decision_closeout") is True,
        },
        {
            "key": "no_database_apply_authorization_issued",
            "claim": package.get("issues_database_apply_authorization") is False,
        },
        {
            "key": "no_secret_material_included",
            "claim": package.get("reads_secret_in_preview") is False,
        },
        {
            "key": "no_shell_sql_or_database_execution",
            "claim": side_effect_free,
        },
        {
            "key": "target_migration_hash_locked",
            "claim": package.get("hash_matches") is True,
        },
        {
            "key": "same_run_production_truth_required",
            "claim": package.get("requires_fresh_production_truth_in_same_run") is True,
        },
        {
            "key": "post_apply_verifier_required",
            "claim": package.get("requires_post_apply_verifier") is True,
        },
        {
            "key": "direct_apply_rejected_until_issuer_lane",
            "claim": "direct_database_apply_requested_from_decision_preflight"
            in rejection_policy,
        },
    ]
    checks = [
        _authorization_issuer_gate_check(
            "decision_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_READY"
            and decision.get("ready_for_future_authorization_decision_closeout") is True
            and package.get("ready_for_future_authorization_decision_package") is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_authorization_decision_closeout": decision.get(
                    "ready_for_future_authorization_decision_closeout"
                ),
                "ready_for_future_authorization_decision_package": package.get(
                    "ready_for_future_authorization_decision_package"
                ),
            },
            "wait_for_decision_closeout",
        ),
        _authorization_issuer_gate_check(
            "nonsecret_envelope_only",
            package.get("operator_secret_boundary") == "future_shell_only"
            and package.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": package.get("operator_secret_boundary"),
                "reads_secret_in_preview": package.get("reads_secret_in_preview"),
            },
            "abort_on_secret_material_in_envelope",
        ),
        _authorization_issuer_gate_check(
            "source_chain_ids_present",
            bool(decision.get("closeout_id"))
            and bool(package.get("source_preflight_id"))
            and bool(package.get("source_lane_guard_id"))
            and bool(package.get("source_closeout_package_id"))
            and bool(package.get("source_intake_id"))
            and bool(package.get("source_closeout_boundary_id")),
            {
                "decision_closeout_id": decision.get("closeout_id"),
                "source_preflight_id": package.get("source_preflight_id"),
                "source_lane_guard_id": package.get("source_lane_guard_id"),
                "source_closeout_package_id": package.get("source_closeout_package_id"),
                "source_intake_id": package.get("source_intake_id"),
                "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_issuer_gate_check(
            "same_run_production_truth_required",
            "fresh_production_truth_same_run" in source_input_keys
            and package.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "input_keys": sorted(key for key in source_input_keys if key),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_issuer_gate_check(
            "post_apply_verifier_required",
            "post_apply_verifier_reference" in source_input_keys
            and package.get("requires_post_apply_verifier") is True
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "input_keys": sorted(key for key in source_input_keys if key),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier_artifact",
        ),
        _authorization_issuer_gate_check(
            "migration_target_hash_locked",
            bool(package.get("target_file"))
            and bool(package.get("expected_sha256"))
            and package.get("hash_matches") is True,
            {
                "target_file": package.get("target_file"),
                "hash_matches": package.get("hash_matches"),
            },
            "abort_on_migration_hash_gap",
        ),
        _authorization_issuer_gate_check(
            "decision_package_is_no_authorization",
            package.get("issues_database_apply_authorization") is False
            and package.get("ready_for_database_apply_now") is False,
            {
                "issues_database_apply_authorization": package.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": package.get("ready_for_database_apply_now"),
            },
            "block_if_package_authorizes_apply",
        ),
        _authorization_issuer_gate_check(
            "closeout_contract_is_no_write",
            contract.get("issues_database_apply_authorization") is False
            and contract.get("ready_for_database_apply_now") is False
            and contract.get("writes_database") is False
            and contract.get("executes_in_preview") is False,
            {
                "issues_database_apply_authorization": contract.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": contract.get("ready_for_database_apply_now"),
                "writes_database": contract.get("writes_database"),
                "executes_in_preview": contract.get("executes_in_preview"),
            },
            "block_if_contract_authorizes_write",
        ),
        _authorization_issuer_gate_check(
            "preview_has_no_side_effects",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
            },
            "abort_on_preview_side_effect",
        ),
        _authorization_issuer_gate_check(
            "direct_apply_still_rejected",
            "direct_database_apply_requested_from_decision_preflight" in rejection_policy
            and package.get("issues_database_apply_authorization") is False
            and package.get("ready_for_database_apply_now") is False,
            {
                "rejection_reason_present": (
                    "direct_database_apply_requested_from_decision_preflight" in rejection_policy
                ),
                "issues_database_apply_authorization": package.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": package.get("ready_for_database_apply_now"),
            },
            "reject_direct_database_apply_from_issuer_gate",
        ),
        _authorization_issuer_gate_check(
            "issuer_policy_requires_future_explicit_authorization",
            len(required_issuer_evidence) == 9
            and len(nonsecret_authorization_claims) == 8
            and all(item.get("required") is True for item in required_issuer_evidence),
            {
                "required_issuer_evidence_count": len(required_issuer_evidence),
                "nonsecret_authorization_claim_count": len(nonsecret_authorization_claims),
            },
            "wait_for_complete_nonsecret_issuer_envelope",
        ),
        _authorization_issuer_gate_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and decision.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": decision.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    issuer_ready = not waiting_checks
    issuer_status = (
        "DB_APPLY_AUTHORIZATION_ISSUER_GATE_READY"
        if issuer_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT"
    )
    issuer_gate_id = _db_apply_authorization_issuer_gate_id(closeout)
    future_authorization_issuer_gate = {
        "gate_id": issuer_gate_id,
        "source_decision_closeout_id": decision.get("closeout_id"),
        "source_decision_preflight_id": package.get("source_preflight_id"),
        "source_lane_guard_id": package.get("source_lane_guard_id"),
        "source_closeout_package_id": package.get("source_closeout_package_id"),
        "source_intake_id": package.get("source_intake_id"),
        "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
        "status": issuer_status,
        "ready_for_future_authorization_issuer_lane": issuer_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    final_nonsecret_authorization_envelope = {
        "envelope_id": issuer_gate_id,
        "source_decision_closeout_id": decision.get("closeout_id"),
        "source_decision_package_id": package.get("package_id"),
        "source_decision_preflight_id": package.get("source_preflight_id"),
        "source_lane_guard_id": package.get("source_lane_guard_id"),
        "source_closeout_package_id": package.get("source_closeout_package_id"),
        "source_intake_id": package.get("source_intake_id"),
        "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
        "status": issuer_status,
        "authorization_material_type": "nonsecret_request_envelope",
        "decision_scope": "future_explicit_db_apply_authorization_issuer_lane_only",
        "ready_for_future_authorization_issuer_lane": issuer_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "target_file": package.get("target_file"),
        "expected_sha256": package.get("expected_sha256"),
        "actual_sha256": package.get("actual_sha256"),
        "hash_matches": package.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": package.get("post_apply_verifier_endpoint"),
        "operator_secret_boundary": "future_shell_only",
        "secret_material_included": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "nonsecret_authorization_claims": nonsecret_authorization_claims,
        "required_issuer_evidence": required_issuer_evidence,
    }
    issuer_gate_contract = {
        "mode": "future_authorization_issuer_gate_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-issuer-gate"
        ),
        "source_decision_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_authorization_issuer_lane": issuer_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_ISSUER_GATE_POLICY,
        "result": issuer_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_issuer_gate_ready_count": 1 if issuer_ready else 0,
            "issuer_gate_check_count": len(checks),
            "issuer_gate_pass_count": passed_count,
            "issuer_gate_waiting_count": len(waiting_checks),
            "authorization_decision_closeout_ready_count": summary.get(
                "authorization_decision_closeout_ready_count", 0
            ),
            "decision_closeout_check_count": summary.get("decision_closeout_check_count", 0),
            "required_issuer_evidence_count": len(required_issuer_evidence),
            "nonsecret_authorization_claim_count": len(nonsecret_authorization_claims),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "decision_rejection_reason_count": summary.get("decision_rejection_reason_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_issuer_gate": future_authorization_issuer_gate,
        "final_nonsecret_authorization_envelope": final_nonsecret_authorization_envelope,
        "issuer_gate_contract": issuer_gate_contract,
        "issuer_gate_checks": checks,
        "source_decision_closeout_summary": summary,
        "source_decision_closeout_contract": contract,
        "source_decision_rejection_policy": rejection_policy,
        "safety": {
            "read_only_db_apply_authorization_issuer_gate": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this issuer gate to hand a nonsecret envelope to a future explicit authorization signing lane.",
            "Keep database apply authorization signing, secret reads, shell execution, SQL, and DB writes out of this gate.",
            "Require fresh production truth, secret rejection, rollback boundary, and post-apply verifier inside the future issuer run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Prepare a no-secret preflight before any future authorization signing decision."""
    issuer_gate = build_pchome_auto_policy_db_apply_authorization_issuer_gate(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    gate = issuer_gate.get("future_authorization_issuer_gate") or {}
    envelope = issuer_gate.get("final_nonsecret_authorization_envelope") or {}
    contract = issuer_gate.get("issuer_gate_contract") or {}
    summary = issuer_gate.get("summary") or {}
    required_evidence = envelope.get("required_issuer_evidence") or []
    nonsecret_claims = envelope.get("nonsecret_authorization_claims") or []
    rejection_policy = issuer_gate.get("source_decision_rejection_policy") or []
    evidence_keys = {item.get("key") for item in required_evidence}
    claim_keys = {item.get("key") for item in nonsecret_claims}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and envelope.get("reads_secret_in_preview") is False
        and envelope.get("executes_shell_in_preview") is False
        and envelope.get("executes_sql_in_preview") is False
        and envelope.get("writes_database_in_preview") is False
        and gate.get("signs_database_apply_authorization") is False
        and envelope.get("signs_database_apply_authorization") is False
    )
    signing_decision_input_requirements = [
        {
            "key": "fresh_production_truth_same_run",
            "required": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "issuer_gate_id",
            "required": True,
            "source_id": gate.get("gate_id"),
        },
        {
            "key": "nonsecret_authorization_envelope_id",
            "required": True,
            "source_id": envelope.get("envelope_id"),
        },
        {
            "key": "decision_closeout_id",
            "required": True,
            "source_id": envelope.get("source_decision_closeout_id"),
        },
        {
            "key": "decision_preflight_id",
            "required": True,
            "source_id": envelope.get("source_decision_preflight_id"),
        },
        {
            "key": "authorization_lane_guard_id",
            "required": True,
            "source_id": envelope.get("source_lane_guard_id"),
        },
        {
            "key": "migration_target_hash",
            "required": True,
            "target_file": envelope.get("target_file"),
            "expected_sha256": envelope.get("expected_sha256"),
            "hash_matches": envelope.get("hash_matches"),
        },
        {
            "key": "secret_boundary_rejection",
            "required": True,
            "operator_secret_boundary": envelope.get("operator_secret_boundary"),
            "secret_material_included": envelope.get("secret_material_included"),
        },
        {
            "key": "post_apply_verifier_reference",
            "required": True,
            "source_endpoint": envelope.get("post_apply_verifier_endpoint"),
        },
        {
            "key": "no_signing_without_future_explicit_authorization",
            "required": True,
            "signs_database_apply_authorization": False,
        },
    ]
    signing_decision_rejection_policy = [
        "production_truth_missing_or_stale",
        "issuer_gate_not_ready",
        "nonsecret_authorization_envelope_missing_or_mutated",
        "issuer_evidence_missing",
        "nonsecret_claim_failed",
        "migration_hash_missing_or_mismatch",
        "secret_material_present_in_signing_preflight",
        "post_apply_verifier_missing",
        "direct_database_apply_requested_from_signing_preflight",
        "authorization_signing_requested_from_preflight",
        "preview_attempted_shell_sql_or_database_side_effect",
    ]
    checks = [
        _authorization_signing_decision_preflight_check(
            "issuer_gate_ready",
            issuer_gate.get("result") == "DB_APPLY_AUTHORIZATION_ISSUER_GATE_READY"
            and gate.get("ready_for_future_authorization_issuer_lane") is True
            and envelope.get("ready_for_future_authorization_issuer_lane") is True,
            {
                "result": issuer_gate.get("result"),
                "ready_for_future_authorization_issuer_lane": gate.get(
                    "ready_for_future_authorization_issuer_lane"
                ),
                "envelope_ready_for_future_authorization_issuer_lane": envelope.get(
                    "ready_for_future_authorization_issuer_lane"
                ),
            },
            "wait_for_authorization_issuer_gate",
        ),
        _authorization_signing_decision_preflight_check(
            "nonsecret_envelope_complete",
            envelope.get("authorization_material_type") == "nonsecret_request_envelope"
            and bool(envelope.get("envelope_id"))
            and envelope.get("secret_material_included") is False,
            {
                "authorization_material_type": envelope.get("authorization_material_type"),
                "envelope_id": envelope.get("envelope_id"),
                "secret_material_included": envelope.get("secret_material_included"),
            },
            "wait_for_nonsecret_authorization_envelope",
        ),
        _authorization_signing_decision_preflight_check(
            "required_issuer_evidence_complete",
            len(required_evidence) == 9
            and all(item.get("required") is True for item in required_evidence),
            {
                "required_issuer_evidence_count": len(required_evidence),
                "evidence_keys": sorted(key for key in evidence_keys if key),
            },
            "wait_for_required_issuer_evidence",
        ),
        _authorization_signing_decision_preflight_check(
            "nonsecret_claims_complete",
            len(nonsecret_claims) == 8
            and all(item.get("claim") is True for item in nonsecret_claims),
            {
                "nonsecret_authorization_claim_count": len(nonsecret_claims),
                "claim_keys": sorted(key for key in claim_keys if key),
            },
            "wait_for_nonsecret_authorization_claims",
        ),
        _authorization_signing_decision_preflight_check(
            "same_run_production_truth_required",
            "fresh_production_truth_same_run" in evidence_keys
            and envelope.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "evidence_keys": sorted(key for key in evidence_keys if key),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signing_decision_preflight_check(
            "post_apply_verifier_required",
            "post_apply_verifier_reference" in evidence_keys
            and envelope.get("requires_post_apply_verifier") is True
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "evidence_keys": sorted(key for key in evidence_keys if key),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier_artifact",
        ),
        _authorization_signing_decision_preflight_check(
            "migration_target_hash_locked",
            bool(envelope.get("target_file"))
            and bool(envelope.get("expected_sha256"))
            and envelope.get("hash_matches") is True,
            {
                "target_file": envelope.get("target_file"),
                "hash_matches": envelope.get("hash_matches"),
            },
            "abort_on_migration_hash_gap",
        ),
        _authorization_signing_decision_preflight_check(
            "secret_boundary_clean",
            "secret_boundary_rejection" in evidence_keys
            and envelope.get("operator_secret_boundary") == "future_shell_only"
            and envelope.get("secret_material_included") is False
            and envelope.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": envelope.get("operator_secret_boundary"),
                "secret_material_included": envelope.get("secret_material_included"),
                "reads_secret_in_preview": envelope.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signing_decision_preflight_check(
            "source_chain_ids_present",
            bool(gate.get("gate_id"))
            and bool(envelope.get("source_decision_closeout_id"))
            and bool(envelope.get("source_decision_preflight_id"))
            and bool(envelope.get("source_lane_guard_id"))
            and bool(envelope.get("source_closeout_package_id"))
            and bool(envelope.get("source_intake_id"))
            and bool(envelope.get("source_closeout_boundary_id")),
            {
                "gate_id": gate.get("gate_id"),
                "source_decision_closeout_id": envelope.get("source_decision_closeout_id"),
                "source_decision_preflight_id": envelope.get("source_decision_preflight_id"),
                "source_lane_guard_id": envelope.get("source_lane_guard_id"),
                "source_closeout_package_id": envelope.get("source_closeout_package_id"),
                "source_intake_id": envelope.get("source_intake_id"),
                "source_closeout_boundary_id": envelope.get("source_closeout_boundary_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signing_decision_preflight_check(
            "preview_has_no_side_effects",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization": envelope.get(
                    "signs_database_apply_authorization"
                ),
            },
            "abort_on_preview_side_effect",
        ),
        _authorization_signing_decision_preflight_check(
            "signing_and_direct_apply_still_rejected",
            contract.get("signs_database_apply_authorization") is False
            and contract.get("issues_database_apply_authorization") is False
            and contract.get("ready_for_database_apply_now") is False
            and contract.get("writes_database") is False,
            {
                "signs_database_apply_authorization": contract.get(
                    "signs_database_apply_authorization"
                ),
                "issues_database_apply_authorization": contract.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": contract.get("ready_for_database_apply_now"),
                "writes_database": contract.get("writes_database"),
            },
            "reject_signing_or_direct_database_apply_from_preflight",
        ),
        _authorization_signing_decision_preflight_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and gate.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": gate.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    preflight_ready = not waiting_checks
    preflight_status = (
        "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_ISSUER_GATE"
    )
    preflight_id = _db_apply_authorization_signing_decision_preflight_id(issuer_gate)
    future_authorization_signing_decision_preflight = {
        "preflight_id": preflight_id,
        "source_issuer_gate_id": gate.get("gate_id"),
        "source_decision_closeout_id": envelope.get("source_decision_closeout_id"),
        "source_decision_package_id": envelope.get("source_decision_package_id"),
        "source_decision_preflight_id": envelope.get("source_decision_preflight_id"),
        "source_lane_guard_id": envelope.get("source_lane_guard_id"),
        "source_closeout_package_id": envelope.get("source_closeout_package_id"),
        "source_intake_id": envelope.get("source_intake_id"),
        "source_closeout_boundary_id": envelope.get("source_closeout_boundary_id"),
        "status": preflight_status,
        "ready_for_future_signing_decision_preflight": preflight_ready,
        "can_enter_authorization_signing_decision_lane": preflight_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    signing_decision_preflight_envelope = {
        "mode": "authorization_signing_decision_preflight_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-preflight"
        ),
        "source_issuer_gate_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-issuer-gate"
        ),
        "machine_verifiable": True,
        "allows_future_authorization_signing_decision_lane": preflight_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "rejects_direct_database_apply": True,
        "requires_post_apply_verifier": True,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_POLICY,
        "result": preflight_status,
        "success": bool(issuer_gate.get("success")),
        "generated_at": issuer_gate.get("generated_at"),
        "source_policy": issuer_gate.get("policy"),
        "stats": issuer_gate.get("stats") or {},
        "summary": {
            "authorization_signing_decision_preflight_ready_count": 1 if preflight_ready else 0,
            "signing_decision_preflight_check_count": len(checks),
            "signing_decision_preflight_pass_count": passed_count,
            "signing_decision_preflight_waiting_count": len(waiting_checks),
            "authorization_issuer_gate_ready_count": summary.get(
                "authorization_issuer_gate_ready_count", 0
            ),
            "issuer_gate_check_count": summary.get("issuer_gate_check_count", 0),
            "required_issuer_evidence_count": len(required_evidence),
            "nonsecret_authorization_claim_count": len(nonsecret_claims),
            "signing_decision_input_requirement_count": len(signing_decision_input_requirements),
            "signing_decision_rejection_reason_count": len(signing_decision_rejection_policy),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signing_decision_preflight": (
            future_authorization_signing_decision_preflight
        ),
        "signing_decision_preflight_envelope": signing_decision_preflight_envelope,
        "signing_decision_input_requirements": signing_decision_input_requirements,
        "signing_decision_rejection_policy": signing_decision_rejection_policy,
        "signing_decision_preflight_checks": checks,
        "source_issuer_gate_summary": summary,
        "source_issuer_gate_contract": contract,
        "source_nonsecret_authorization_envelope": envelope,
        "safety": {
            "read_only_db_apply_authorization_signing_decision_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preflight to verify the nonsecret envelope before a future explicit signing decision lane.",
            "Keep authorization signing, secret reads, shell execution, SQL, and DB writes out of this preflight.",
            "Require fresh production truth, secret rejection, rollback boundary, and post-apply verifier inside the future signing decision run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out signing-decision preflight as an unsigned package."""
    preflight = build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    decision = preflight.get("future_authorization_signing_decision_preflight") or {}
    envelope = preflight.get("signing_decision_preflight_envelope") or {}
    source_envelope = preflight.get("source_nonsecret_authorization_envelope") or {}
    summary = preflight.get("summary") or {}
    input_requirements = preflight.get("signing_decision_input_requirements") or []
    rejection_policy = preflight.get("signing_decision_rejection_policy") or []
    input_keys = {item.get("key") for item in input_requirements}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and decision.get("signs_database_apply_authorization") is False
        and envelope.get("signs_database_apply_authorization") is False
        and envelope.get("secret_material_required_in_preview") is False
        and source_envelope.get("secret_material_included") is False
        and source_envelope.get("reads_secret_in_preview") is False
        and source_envelope.get("executes_shell_in_preview") is False
        and source_envelope.get("executes_sql_in_preview") is False
        and source_envelope.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signing_decision_closeout_check(
            "signing_decision_preflight_ready",
            preflight.get("result")
            == "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_READY"
            and decision.get("ready_for_future_signing_decision_preflight") is True,
            {
                "result": preflight.get("result"),
                "ready_for_future_signing_decision_preflight": decision.get(
                    "ready_for_future_signing_decision_preflight"
                ),
            },
            "wait_for_signing_decision_preflight",
        ),
        _authorization_signing_decision_closeout_check(
            "preflight_envelope_allows_future_lane_only",
            envelope.get("allows_future_authorization_signing_decision_lane") is True
            and envelope.get("issues_database_apply_authorization") is False
            and envelope.get("ready_for_database_apply_now") is False
            and envelope.get("signs_database_apply_authorization") is False,
            {
                "allows_future_authorization_signing_decision_lane": envelope.get(
                    "allows_future_authorization_signing_decision_lane"
                ),
                "issues_database_apply_authorization": envelope.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": envelope.get("ready_for_database_apply_now"),
                "signs_database_apply_authorization": envelope.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_preflight_envelope_signs_or_authorizes",
        ),
        _authorization_signing_decision_closeout_check(
            "signing_decision_inputs_complete",
            len(input_requirements) == 10
            and all(item.get("required") is True for item in input_requirements),
            {
                "signing_decision_input_requirement_count": len(input_requirements),
                "input_keys": sorted(key for key in input_keys if key),
            },
            "wait_for_signing_decision_input_requirements",
        ),
        _authorization_signing_decision_closeout_check(
            "signing_decision_rejection_policy_complete",
            len(rejection_policy) == 11
            and "authorization_signing_requested_from_preflight" in rejection_policy
            and "direct_database_apply_requested_from_signing_preflight" in rejection_policy,
            {"signing_decision_rejection_reason_count": len(rejection_policy)},
            "wait_for_signing_decision_rejection_policy",
        ),
        _authorization_signing_decision_closeout_check(
            "unsigned_package_source_envelope_complete",
            source_envelope.get("authorization_material_type") == "nonsecret_request_envelope"
            and bool(source_envelope.get("envelope_id"))
            and source_envelope.get("secret_material_included") is False,
            {
                "authorization_material_type": source_envelope.get("authorization_material_type"),
                "envelope_id": source_envelope.get("envelope_id"),
                "secret_material_included": source_envelope.get("secret_material_included"),
            },
            "wait_for_nonsecret_source_envelope",
        ),
        _authorization_signing_decision_closeout_check(
            "source_chain_ids_present",
            bool(decision.get("preflight_id"))
            and bool(decision.get("source_issuer_gate_id"))
            and bool(decision.get("source_decision_closeout_id"))
            and bool(decision.get("source_decision_preflight_id"))
            and bool(decision.get("source_lane_guard_id"))
            and bool(decision.get("source_closeout_package_id"))
            and bool(decision.get("source_intake_id"))
            and bool(decision.get("source_closeout_boundary_id")),
            {
                "preflight_id": decision.get("preflight_id"),
                "source_issuer_gate_id": decision.get("source_issuer_gate_id"),
                "source_decision_closeout_id": decision.get("source_decision_closeout_id"),
                "source_decision_preflight_id": decision.get("source_decision_preflight_id"),
                "source_lane_guard_id": decision.get("source_lane_guard_id"),
                "source_closeout_package_id": decision.get("source_closeout_package_id"),
                "source_intake_id": decision.get("source_intake_id"),
                "source_closeout_boundary_id": decision.get("source_closeout_boundary_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signing_decision_closeout_check(
            "same_run_production_truth_required",
            "fresh_production_truth_same_run" in input_keys
            and source_envelope.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "input_keys": sorted(key for key in input_keys if key),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signing_decision_closeout_check(
            "post_apply_verifier_required",
            "post_apply_verifier_reference" in input_keys
            and source_envelope.get("requires_post_apply_verifier") is True
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "input_keys": sorted(key for key in input_keys if key),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier_artifact",
        ),
        _authorization_signing_decision_closeout_check(
            "migration_target_hash_locked",
            bool(source_envelope.get("target_file"))
            and bool(source_envelope.get("expected_sha256"))
            and source_envelope.get("hash_matches") is True,
            {
                "target_file": source_envelope.get("target_file"),
                "hash_matches": source_envelope.get("hash_matches"),
            },
            "abort_on_migration_hash_gap",
        ),
        _authorization_signing_decision_closeout_check(
            "secret_boundary_clean",
            "secret_boundary_rejection" in input_keys
            and source_envelope.get("operator_secret_boundary") == "future_shell_only"
            and source_envelope.get("secret_material_included") is False
            and source_envelope.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": source_envelope.get("operator_secret_boundary"),
                "secret_material_included": source_envelope.get("secret_material_included"),
                "reads_secret_in_preview": source_envelope.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signing_decision_closeout_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free
            and envelope.get("rejects_direct_database_apply") is True
            and decision.get("issues_database_apply_authorization") is False
            and decision.get("ready_for_database_apply_now") is False,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "rejects_direct_database_apply": envelope.get("rejects_direct_database_apply"),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
        _authorization_signing_decision_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and decision.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": decision.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT"
    )
    closeout_id = _db_apply_authorization_signing_decision_closeout_id(preflight)
    future_authorization_signing_decision_closeout = {
        "closeout_id": closeout_id,
        "source_signing_decision_preflight_id": decision.get("preflight_id"),
        "source_issuer_gate_id": decision.get("source_issuer_gate_id"),
        "source_decision_closeout_id": decision.get("source_decision_closeout_id"),
        "source_decision_package_id": decision.get("source_decision_package_id"),
        "source_decision_preflight_id": decision.get("source_decision_preflight_id"),
        "source_lane_guard_id": decision.get("source_lane_guard_id"),
        "source_closeout_package_id": decision.get("source_closeout_package_id"),
        "source_intake_id": decision.get("source_intake_id"),
        "source_closeout_boundary_id": decision.get("source_closeout_boundary_id"),
        "status": closeout_status,
        "ready_for_future_signing_decision_closeout": closeout_ready,
        "can_enter_unsigned_signing_decision_package_lane": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    unsigned_signing_decision_package = {
        "package_id": closeout_id,
        "source_signing_decision_preflight_id": decision.get("preflight_id"),
        "source_issuer_gate_id": decision.get("source_issuer_gate_id"),
        "source_nonsecret_envelope_id": source_envelope.get("envelope_id"),
        "source_decision_closeout_id": decision.get("source_decision_closeout_id"),
        "source_decision_package_id": decision.get("source_decision_package_id"),
        "source_decision_preflight_id": decision.get("source_decision_preflight_id"),
        "source_lane_guard_id": decision.get("source_lane_guard_id"),
        "source_closeout_package_id": decision.get("source_closeout_package_id"),
        "source_intake_id": decision.get("source_intake_id"),
        "source_closeout_boundary_id": decision.get("source_closeout_boundary_id"),
        "status": closeout_status,
        "ready_for_future_unsigned_signing_decision_package": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "decision_scope": "future_explicit_db_apply_authorization_signing_decision_only",
        "authorization_material_type": "unsigned_signing_decision_package",
        "target_file": source_envelope.get("target_file"),
        "expected_sha256": source_envelope.get("expected_sha256"),
        "actual_sha256": source_envelope.get("actual_sha256"),
        "hash_matches": source_envelope.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": source_envelope.get("post_apply_verifier_endpoint"),
        "operator_secret_boundary": "future_shell_only",
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "signing_decision_input_requirements": input_requirements,
        "signing_decision_rejection_policy": rejection_policy,
    }
    signing_decision_closeout_contract = {
        "mode": "unsigned_signing_decision_closeout_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-closeout"
        ),
        "source_signing_decision_preflight_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-preflight"
        ),
        "machine_verifiable": True,
        "permits_future_unsigned_signing_decision_package_lane": closeout_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(preflight.get("success")),
        "generated_at": preflight.get("generated_at"),
        "source_policy": preflight.get("policy"),
        "stats": preflight.get("stats") or {},
        "summary": {
            "authorization_signing_decision_closeout_ready_count": 1 if closeout_ready else 0,
            "signing_decision_closeout_check_count": len(checks),
            "signing_decision_closeout_pass_count": passed_count,
            "signing_decision_closeout_waiting_count": len(waiting_checks),
            "authorization_signing_decision_preflight_ready_count": summary.get(
                "authorization_signing_decision_preflight_ready_count", 0
            ),
            "signing_decision_preflight_check_count": summary.get(
                "signing_decision_preflight_check_count", 0
            ),
            "signing_decision_input_requirement_count": len(input_requirements),
            "signing_decision_rejection_reason_count": len(rejection_policy),
            "required_issuer_evidence_count": summary.get("required_issuer_evidence_count", 0),
            "nonsecret_authorization_claim_count": summary.get(
                "nonsecret_authorization_claim_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signing_decision_closeout": (
            future_authorization_signing_decision_closeout
        ),
        "unsigned_signing_decision_package": unsigned_signing_decision_package,
        "signing_decision_closeout_contract": signing_decision_closeout_contract,
        "signing_decision_closeout_checks": checks,
        "source_signing_decision_preflight_summary": summary,
        "source_signing_decision_preflight_envelope": envelope,
        "source_nonsecret_authorization_envelope": source_envelope,
        "safety": {
            "read_only_db_apply_authorization_signing_decision_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the unsigned package for a future explicit authorization signing decision lane.",
            "Keep authorization signing, secret reads, shell execution, SQL, and DB writes out of this closeout.",
            "Require fresh production truth, secret rejection, rollback boundary, and post-apply verifier inside the future signing decision run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Guard the future signing issuer lane without issuing authorization."""
    closeout = build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    signing_closeout = closeout.get("future_authorization_signing_decision_closeout") or {}
    package = closeout.get("unsigned_signing_decision_package") or {}
    contract = closeout.get("signing_decision_closeout_contract") or {}
    summary = closeout.get("summary") or {}
    input_requirements = package.get("signing_decision_input_requirements") or []
    rejection_policy = package.get("signing_decision_rejection_policy") or []
    input_keys = {item.get("key") for item in input_requirements}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and signing_closeout.get("signs_database_apply_authorization") is False
        and package.get("signs_database_apply_authorization") is False
        and package.get("secret_material_included") is False
        and package.get("secret_material_required_in_preview") is False
        and package.get("reads_secret_in_preview") is False
        and package.get("executes_shell_in_preview") is False
        and package.get("executes_sql_in_preview") is False
        and package.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signing_issuer_guard_check(
            "signing_decision_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_READY"
            and signing_closeout.get("ready_for_future_signing_decision_closeout") is True
            and package.get("ready_for_future_unsigned_signing_decision_package") is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_signing_decision_closeout": signing_closeout.get(
                    "ready_for_future_signing_decision_closeout"
                ),
                "ready_for_future_unsigned_signing_decision_package": package.get(
                    "ready_for_future_unsigned_signing_decision_package"
                ),
            },
            "wait_for_signing_decision_closeout",
        ),
        _authorization_signing_issuer_guard_check(
            "unsigned_signing_decision_package_complete",
            package.get("authorization_material_type") == "unsigned_signing_decision_package"
            and bool(package.get("package_id"))
            and package.get("ready_for_future_unsigned_signing_decision_package") is True,
            {
                "authorization_material_type": package.get("authorization_material_type"),
                "package_id": package.get("package_id"),
                "ready_for_future_unsigned_signing_decision_package": package.get(
                    "ready_for_future_unsigned_signing_decision_package"
                ),
            },
            "wait_for_unsigned_signing_decision_package",
        ),
        _authorization_signing_issuer_guard_check(
            "unsigned_package_is_no_authorization_or_signing",
            package.get("issues_database_apply_authorization") is False
            and package.get("ready_for_database_apply_now") is False
            and package.get("signs_database_apply_authorization") is False,
            {
                "issues_database_apply_authorization": package.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": package.get("ready_for_database_apply_now"),
                "signs_database_apply_authorization": package.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_unsigned_package_authorizes_or_signs",
        ),
        _authorization_signing_issuer_guard_check(
            "source_chain_ids_present",
            bool(signing_closeout.get("closeout_id"))
            and bool(package.get("source_signing_decision_preflight_id"))
            and bool(package.get("source_issuer_gate_id"))
            and bool(package.get("source_nonsecret_envelope_id"))
            and bool(package.get("source_decision_closeout_id"))
            and bool(package.get("source_decision_preflight_id"))
            and bool(package.get("source_lane_guard_id"))
            and bool(package.get("source_closeout_package_id"))
            and bool(package.get("source_intake_id"))
            and bool(package.get("source_closeout_boundary_id")),
            {
                "closeout_id": signing_closeout.get("closeout_id"),
                "source_signing_decision_preflight_id": package.get(
                    "source_signing_decision_preflight_id"
                ),
                "source_issuer_gate_id": package.get("source_issuer_gate_id"),
                "source_nonsecret_envelope_id": package.get("source_nonsecret_envelope_id"),
                "source_decision_closeout_id": package.get("source_decision_closeout_id"),
                "source_decision_preflight_id": package.get("source_decision_preflight_id"),
                "source_lane_guard_id": package.get("source_lane_guard_id"),
                "source_closeout_package_id": package.get("source_closeout_package_id"),
                "source_intake_id": package.get("source_intake_id"),
                "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signing_issuer_guard_check(
            "same_run_production_truth_required",
            "fresh_production_truth_same_run" in input_keys
            and package.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "input_keys": sorted(key for key in input_keys if key),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signing_issuer_guard_check(
            "post_apply_verifier_required",
            "post_apply_verifier_reference" in input_keys
            and package.get("requires_post_apply_verifier") is True
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "input_keys": sorted(key for key in input_keys if key),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier_artifact",
        ),
        _authorization_signing_issuer_guard_check(
            "migration_target_hash_locked",
            bool(package.get("target_file"))
            and bool(package.get("expected_sha256"))
            and package.get("hash_matches") is True,
            {
                "target_file": package.get("target_file"),
                "hash_matches": package.get("hash_matches"),
            },
            "abort_on_migration_hash_gap",
        ),
        _authorization_signing_issuer_guard_check(
            "secret_boundary_clean",
            "secret_boundary_rejection" in input_keys
            and package.get("operator_secret_boundary") == "future_shell_only"
            and package.get("secret_material_included") is False
            and package.get("secret_material_required_in_preview") is False
            and package.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": package.get("operator_secret_boundary"),
                "secret_material_included": package.get("secret_material_included"),
                "secret_material_required_in_preview": package.get(
                    "secret_material_required_in_preview"
                ),
                "reads_secret_in_preview": package.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signing_issuer_guard_check(
            "signing_inputs_and_rejection_policy_complete",
            len(input_requirements) == 10
            and len(rejection_policy) == 11
            and "authorization_signing_requested_from_preflight" in rejection_policy
            and "direct_database_apply_requested_from_signing_preflight" in rejection_policy,
            {
                "signing_decision_input_requirement_count": len(input_requirements),
                "signing_decision_rejection_reason_count": len(rejection_policy),
            },
            "wait_for_signing_inputs_and_rejection_policy",
        ),
        _authorization_signing_issuer_guard_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free
            and signing_closeout.get("issues_database_apply_authorization") is False
            and signing_closeout.get("ready_for_database_apply_now") is False,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
        _authorization_signing_issuer_guard_check(
            "signable_boundary_is_future_only",
            contract.get("permits_future_unsigned_signing_decision_package_lane") is True
            and contract.get("issues_database_apply_authorization") is False
            and contract.get("ready_for_database_apply_now") is False
            and contract.get("signs_database_apply_authorization") is False
            and contract.get("writes_database") is False,
            {
                "permits_future_unsigned_signing_decision_package_lane": contract.get(
                    "permits_future_unsigned_signing_decision_package_lane"
                ),
                "issues_database_apply_authorization": contract.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": contract.get("ready_for_database_apply_now"),
                "signs_database_apply_authorization": contract.get(
                    "signs_database_apply_authorization"
                ),
                "writes_database": contract.get("writes_database"),
            },
            "block_if_signable_boundary_authorizes_now",
        ),
        _authorization_signing_issuer_guard_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and signing_closeout.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": signing_closeout.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    guard_ready = not waiting_checks
    guard_status = (
        "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_READY"
        if guard_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT"
    )
    guard_id = _db_apply_authorization_signing_issuer_guard_id(closeout)
    future_authorization_signing_issuer_guard = {
        "guard_id": guard_id,
        "source_signing_decision_closeout_id": signing_closeout.get("closeout_id"),
        "source_signing_decision_preflight_id": package.get(
            "source_signing_decision_preflight_id"
        ),
        "source_issuer_gate_id": package.get("source_issuer_gate_id"),
        "source_nonsecret_envelope_id": package.get("source_nonsecret_envelope_id"),
        "source_decision_closeout_id": package.get("source_decision_closeout_id"),
        "source_decision_preflight_id": package.get("source_decision_preflight_id"),
        "source_lane_guard_id": package.get("source_lane_guard_id"),
        "source_closeout_package_id": package.get("source_closeout_package_id"),
        "source_intake_id": package.get("source_intake_id"),
        "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
        "status": guard_status,
        "ready_for_future_signing_issuer_guard": guard_ready,
        "can_enter_future_authorization_signing_issuer_lane": guard_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    signable_request_boundary = {
        "boundary_id": guard_id,
        "source_signing_decision_closeout_id": signing_closeout.get("closeout_id"),
        "source_unsigned_signing_decision_package_id": package.get("package_id"),
        "source_signing_decision_preflight_id": package.get(
            "source_signing_decision_preflight_id"
        ),
        "source_issuer_gate_id": package.get("source_issuer_gate_id"),
        "source_nonsecret_envelope_id": package.get("source_nonsecret_envelope_id"),
        "source_decision_closeout_id": package.get("source_decision_closeout_id"),
        "source_decision_preflight_id": package.get("source_decision_preflight_id"),
        "source_lane_guard_id": package.get("source_lane_guard_id"),
        "source_closeout_package_id": package.get("source_closeout_package_id"),
        "source_intake_id": package.get("source_intake_id"),
        "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
        "status": guard_status,
        "request_boundary_type": "future_signable_request_boundary",
        "ready_for_future_signable_request_boundary": guard_ready,
        "can_enter_future_authorization_signing_issuer_lane": guard_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "target_file": package.get("target_file"),
        "expected_sha256": package.get("expected_sha256"),
        "actual_sha256": package.get("actual_sha256"),
        "hash_matches": package.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": package.get("post_apply_verifier_endpoint"),
        "operator_secret_boundary": "future_shell_only",
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "signing_decision_input_requirement_count": len(input_requirements),
        "signing_decision_rejection_reason_count": len(rejection_policy),
    }
    signing_issuer_guard_contract = {
        "mode": "future_signing_issuer_guard_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-guard"
        ),
        "source_signing_decision_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_authorization_signing_issuer_lane": guard_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_POLICY,
        "result": guard_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_signing_issuer_guard_ready_count": 1 if guard_ready else 0,
            "signing_issuer_guard_check_count": len(checks),
            "signing_issuer_guard_pass_count": passed_count,
            "signing_issuer_guard_waiting_count": len(waiting_checks),
            "authorization_signing_decision_closeout_ready_count": summary.get(
                "authorization_signing_decision_closeout_ready_count", 0
            ),
            "signing_decision_closeout_check_count": summary.get(
                "signing_decision_closeout_check_count", 0
            ),
            "signing_decision_input_requirement_count": len(input_requirements),
            "signing_decision_rejection_reason_count": len(rejection_policy),
            "required_issuer_evidence_count": summary.get("required_issuer_evidence_count", 0),
            "nonsecret_authorization_claim_count": summary.get(
                "nonsecret_authorization_claim_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signing_issuer_guard": future_authorization_signing_issuer_guard,
        "signable_request_boundary": signable_request_boundary,
        "signing_issuer_guard_contract": signing_issuer_guard_contract,
        "signing_issuer_guard_checks": checks,
        "source_signing_decision_closeout_summary": summary,
        "source_signing_decision_closeout_contract": contract,
        "source_unsigned_signing_decision_package": package,
        "safety": {
            "read_only_db_apply_authorization_signing_issuer_guard": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this guard to pass a signable request boundary to a future explicit authorization signing issuer lane.",
            "Keep authorization signing, secret reads, shell execution, SQL, and DB writes out of this guard.",
            "Require fresh production truth, secret rejection, rollback boundary, and post-apply verifier inside the future signing issuer run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the future signing issuer boundary without signing authorization."""
    guard = build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    issuer_guard = guard.get("future_authorization_signing_issuer_guard") or {}
    boundary = guard.get("signable_request_boundary") or {}
    contract = guard.get("signing_issuer_guard_contract") or {}
    summary = guard.get("summary") or {}
    safety = guard.get("safety") or {}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and boundary.get("secret_material_included") is False
        and boundary.get("secret_material_required_in_preview") is False
        and boundary.get("reads_secret_in_preview") is False
        and boundary.get("executes_shell_in_preview") is False
        and boundary.get("executes_sql_in_preview") is False
        and boundary.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signing_issuer_closeout_check(
            "signing_issuer_guard_ready",
            guard.get("result") == "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_READY"
            and issuer_guard.get("ready_for_future_signing_issuer_guard") is True
            and boundary.get("ready_for_future_signable_request_boundary") is True,
            {
                "result": guard.get("result"),
                "ready_for_future_signing_issuer_guard": issuer_guard.get(
                    "ready_for_future_signing_issuer_guard"
                ),
                "ready_for_future_signable_request_boundary": boundary.get(
                    "ready_for_future_signable_request_boundary"
                ),
            },
            "wait_for_signing_issuer_guard",
        ),
        _authorization_signing_issuer_closeout_check(
            "final_signable_boundary_complete",
            bool(boundary.get("boundary_id"))
            and boundary.get("request_boundary_type") == "future_signable_request_boundary"
            and boundary.get("can_enter_future_authorization_signing_issuer_lane") is True,
            {
                "boundary_id": boundary.get("boundary_id"),
                "request_boundary_type": boundary.get("request_boundary_type"),
                "can_enter_future_authorization_signing_issuer_lane": boundary.get(
                    "can_enter_future_authorization_signing_issuer_lane"
                ),
            },
            "wait_for_signable_request_boundary",
        ),
        _authorization_signing_issuer_closeout_check(
            "source_chain_ids_present",
            bool(issuer_guard.get("guard_id"))
            and bool(boundary.get("source_signing_decision_closeout_id"))
            and bool(boundary.get("source_unsigned_signing_decision_package_id"))
            and bool(boundary.get("source_signing_decision_preflight_id"))
            and bool(boundary.get("source_issuer_gate_id"))
            and bool(boundary.get("source_nonsecret_envelope_id"))
            and bool(boundary.get("source_decision_closeout_id"))
            and bool(boundary.get("source_decision_preflight_id"))
            and bool(boundary.get("source_lane_guard_id"))
            and bool(boundary.get("source_closeout_package_id"))
            and bool(boundary.get("source_intake_id"))
            and bool(boundary.get("source_closeout_boundary_id")),
            {
                "guard_id": issuer_guard.get("guard_id"),
                "source_signing_decision_closeout_id": boundary.get(
                    "source_signing_decision_closeout_id"
                ),
                "source_unsigned_signing_decision_package_id": boundary.get(
                    "source_unsigned_signing_decision_package_id"
                ),
                "source_issuer_gate_id": boundary.get("source_issuer_gate_id"),
                "source_nonsecret_envelope_id": boundary.get("source_nonsecret_envelope_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signing_issuer_closeout_check(
            "same_run_production_truth_required",
            boundary.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": boundary.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signing_issuer_closeout_check(
            "post_apply_verifier_required",
            boundary.get("requires_post_apply_verifier") is True
            and bool(boundary.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_post_apply_verifier": boundary.get("requires_post_apply_verifier"),
                "post_apply_verifier_endpoint": boundary.get("post_apply_verifier_endpoint"),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier",
        ),
        _authorization_signing_issuer_closeout_check(
            "migration_file_hash_locked",
            boundary.get("target_file") == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and boundary.get("hash_matches") is True
            and bool(boundary.get("expected_sha256"))
            and boundary.get("expected_sha256") == boundary.get("actual_sha256"),
            {
                "target_file": boundary.get("target_file"),
                "hash_matches": boundary.get("hash_matches"),
                "expected_sha256": boundary.get("expected_sha256"),
                "actual_sha256": boundary.get("actual_sha256"),
            },
            "abort_on_migration_file_hash_mismatch",
        ),
        _authorization_signing_issuer_closeout_check(
            "signing_inputs_and_rejection_policy_carried_forward",
            int(summary.get("signing_decision_input_requirement_count") or 0) == 10
            and int(summary.get("signing_decision_rejection_reason_count") or 0) == 11
            and boundary.get("signing_decision_input_requirement_count") == 10
            and boundary.get("signing_decision_rejection_reason_count") == 11,
            {
                "signing_decision_input_requirement_count": summary.get(
                    "signing_decision_input_requirement_count", 0
                ),
                "signing_decision_rejection_reason_count": summary.get(
                    "signing_decision_rejection_reason_count", 0
                ),
            },
            "wait_for_signing_input_contract",
        ),
        _authorization_signing_issuer_closeout_check(
            "contract_is_future_only_and_non_executing",
            contract.get("permits_future_authorization_signing_issuer_lane") is True
            and contract.get("issues_database_apply_authorization") is False
            and contract.get("ready_for_database_apply_now") is False
            and contract.get("signs_database_apply_authorization") is False
            and contract.get("writes_database") is False
            and contract.get("executes_in_preview") is False,
            {
                "permits_future_authorization_signing_issuer_lane": contract.get(
                    "permits_future_authorization_signing_issuer_lane"
                ),
                "issues_database_apply_authorization": contract.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": contract.get("ready_for_database_apply_now"),
                "signs_database_apply_authorization": contract.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_contract_authorizes_or_executes",
        ),
        _authorization_signing_issuer_closeout_check(
            "signable_boundary_has_no_secret_material",
            boundary.get("operator_secret_boundary") == "future_shell_only"
            and boundary.get("secret_material_included") is False
            and boundary.get("secret_material_required_in_preview") is False
            and boundary.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": boundary.get("operator_secret_boundary"),
                "secret_material_included": boundary.get("secret_material_included"),
                "secret_material_required_in_preview": boundary.get(
                    "secret_material_required_in_preview"
                ),
                "reads_secret_in_preview": boundary.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signing_issuer_closeout_check(
            "final_package_does_not_authorize_sign_or_apply",
            issuer_guard.get("issues_database_apply_authorization") is False
            and issuer_guard.get("ready_for_database_apply_now") is False
            and issuer_guard.get("signs_database_apply_authorization") is False
            and boundary.get("issues_database_apply_authorization") is False
            and boundary.get("ready_for_database_apply_now") is False
            and boundary.get("signs_database_apply_authorization") is False,
            {
                "issuer_guard_issues_database_apply_authorization": issuer_guard.get(
                    "issues_database_apply_authorization"
                ),
                "issuer_guard_ready_for_database_apply_now": issuer_guard.get(
                    "ready_for_database_apply_now"
                ),
                "boundary_signs_database_apply_authorization": boundary.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_closeout_authorizes_signs_or_applies",
        ),
        _authorization_signing_issuer_closeout_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free,
            {
                "writes_script_count": summary.get("writes_script_count", 0),
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
        _authorization_signing_issuer_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and issuer_guard.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": issuer_guard.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD"
    )
    closeout_id = _db_apply_authorization_signing_issuer_closeout_id(guard)
    future_authorization_signing_issuer_closeout = {
        "closeout_id": closeout_id,
        "source_signing_issuer_guard_id": issuer_guard.get("guard_id"),
        "source_signable_request_boundary_id": boundary.get("boundary_id"),
        "source_signing_decision_closeout_id": boundary.get(
            "source_signing_decision_closeout_id"
        ),
        "source_unsigned_signing_decision_package_id": boundary.get(
            "source_unsigned_signing_decision_package_id"
        ),
        "source_signing_decision_preflight_id": boundary.get(
            "source_signing_decision_preflight_id"
        ),
        "source_issuer_gate_id": boundary.get("source_issuer_gate_id"),
        "source_nonsecret_envelope_id": boundary.get("source_nonsecret_envelope_id"),
        "source_decision_closeout_id": boundary.get("source_decision_closeout_id"),
        "source_decision_preflight_id": boundary.get("source_decision_preflight_id"),
        "source_lane_guard_id": boundary.get("source_lane_guard_id"),
        "source_closeout_package_id": boundary.get("source_closeout_package_id"),
        "source_intake_id": boundary.get("source_intake_id"),
        "source_closeout_boundary_id": boundary.get("source_closeout_boundary_id"),
        "status": closeout_status,
        "ready_for_future_signing_issuer_closeout": closeout_ready,
        "can_enter_future_final_signable_request_package_lane": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    final_signable_request_package = {
        "package_id": closeout_id,
        "source_signing_issuer_guard_id": issuer_guard.get("guard_id"),
        "source_signable_request_boundary_id": boundary.get("boundary_id"),
        "source_unsigned_signing_decision_package_id": boundary.get(
            "source_unsigned_signing_decision_package_id"
        ),
        "source_signing_decision_closeout_id": boundary.get(
            "source_signing_decision_closeout_id"
        ),
        "source_signing_decision_preflight_id": boundary.get(
            "source_signing_decision_preflight_id"
        ),
        "source_issuer_gate_id": boundary.get("source_issuer_gate_id"),
        "source_nonsecret_envelope_id": boundary.get("source_nonsecret_envelope_id"),
        "source_decision_closeout_id": boundary.get("source_decision_closeout_id"),
        "source_decision_preflight_id": boundary.get("source_decision_preflight_id"),
        "source_lane_guard_id": boundary.get("source_lane_guard_id"),
        "source_closeout_package_id": boundary.get("source_closeout_package_id"),
        "source_intake_id": boundary.get("source_intake_id"),
        "source_closeout_boundary_id": boundary.get("source_closeout_boundary_id"),
        "status": closeout_status,
        "authorization_material_type": "final_signable_request_package",
        "ready_for_future_final_signable_request_package": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "target_file": boundary.get("target_file"),
        "expected_sha256": boundary.get("expected_sha256"),
        "actual_sha256": boundary.get("actual_sha256"),
        "hash_matches": boundary.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": boundary.get("post_apply_verifier_endpoint"),
        "operator_secret_boundary": "future_shell_only",
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "signing_decision_input_requirement_count": boundary.get(
            "signing_decision_input_requirement_count"
        ),
        "signing_decision_rejection_reason_count": boundary.get(
            "signing_decision_rejection_reason_count"
        ),
    }
    signing_issuer_closeout_contract = {
        "mode": "final_signable_request_closeout_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-closeout"
        ),
        "source_signing_issuer_guard_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-guard"
        ),
        "machine_verifiable": True,
        "permits_future_final_signable_request_package_lane": closeout_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(guard.get("success")),
        "generated_at": guard.get("generated_at"),
        "source_policy": guard.get("policy"),
        "stats": guard.get("stats") or {},
        "summary": {
            "authorization_signing_issuer_closeout_ready_count": 1 if closeout_ready else 0,
            "signing_issuer_closeout_check_count": len(checks),
            "signing_issuer_closeout_pass_count": passed_count,
            "signing_issuer_closeout_waiting_count": len(waiting_checks),
            "authorization_signing_issuer_guard_ready_count": summary.get(
                "authorization_signing_issuer_guard_ready_count", 0
            ),
            "signing_issuer_guard_check_count": summary.get(
                "signing_issuer_guard_check_count", 0
            ),
            "signing_issuer_guard_pass_count": summary.get(
                "signing_issuer_guard_pass_count", 0
            ),
            "signing_decision_input_requirement_count": summary.get(
                "signing_decision_input_requirement_count", 0
            ),
            "signing_decision_rejection_reason_count": summary.get(
                "signing_decision_rejection_reason_count", 0
            ),
            "required_issuer_evidence_count": summary.get("required_issuer_evidence_count", 0),
            "nonsecret_authorization_claim_count": summary.get(
                "nonsecret_authorization_claim_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signing_issuer_closeout": (
            future_authorization_signing_issuer_closeout
        ),
        "final_signable_request_package": final_signable_request_package,
        "signing_issuer_closeout_contract": signing_issuer_closeout_contract,
        "signing_issuer_closeout_checks": checks,
        "source_signing_issuer_guard_summary": summary,
        "source_signing_issuer_guard_contract": contract,
        "source_signable_request_boundary": boundary,
        "safety": {
            "read_only_db_apply_authorization_signing_issuer_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the final signable request package for a future explicit authorization signing lane.",
            "Keep authorization signing, secret reads, shell execution, SQL, and DB writes out of this closeout.",
            "Require fresh production truth, operator-held secret material, rollback boundary, and post-apply verifier inside the future signing run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Preflight a future explicit authorization signing execution without signing."""
    closeout = build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    issuer_closeout = closeout.get("future_authorization_signing_issuer_closeout") or {}
    final_package = closeout.get("final_signable_request_package") or {}
    closeout_contract = closeout.get("signing_issuer_closeout_contract") or {}
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    preflight_id = _db_apply_authorization_signing_execution_preflight_id(closeout)

    required_nonsecret_inputs = [
        {
            "key": "final_signable_request_package_id",
            "value": final_package.get("package_id"),
            "secret": False,
        },
        {
            "key": "signing_issuer_closeout_id",
            "value": issuer_closeout.get("closeout_id"),
            "secret": False,
        },
        {"key": "target_file", "value": final_package.get("target_file"), "secret": False},
        {
            "key": "migration_expected_sha256",
            "value": final_package.get("expected_sha256"),
            "secret": False,
        },
        {
            "key": "migration_actual_sha256",
            "value": final_package.get("actual_sha256"),
            "secret": False,
        },
        {
            "key": "same_run_production_truth",
            "value": "required_before_future_signing_execution",
            "secret": False,
        },
        {
            "key": "post_apply_verifier_endpoint",
            "value": final_package.get("post_apply_verifier_endpoint"),
            "secret": False,
        },
        {
            "key": "rollback_boundary",
            "value": "required_before_future_db_apply",
            "secret": False,
        },
        {
            "key": "abort_conditions",
            "value": "fail_closed_before_future_signing_execution",
            "secret": False,
        },
        {
            "key": "operator_held_secret_reference",
            "value": "external_runtime_reference_only",
            "secret": False,
        },
    ]
    abort_conditions = [
        "abort_if_production_truth_missing_or_stale",
        "abort_if_final_signable_request_package_not_ready",
        "abort_if_migration_hash_mismatch",
        "abort_if_post_apply_verifier_missing",
        "abort_if_secret_value_enters_preview_payload",
        "abort_if_future_runner_cannot_use_check_mode",
        "abort_if_authorization_signing_would_write_database",
        "abort_if_manual_review_gate_reappears_in_primary_flow",
    ]
    rollback_boundary = [
        "capture_prewrite_snapshot_before_future_apply",
        "keep_migration_rollback_sql_bound_to_same_hash",
        "require_post_apply_readback_before_success_receipt",
        "route_failed_verifier_to_exception_only_auto_resolution",
    ]
    operator_held_secret_boundary_contract = {
        "mode": "operator_held_secret_reference_only",
        "secret_material_owner": "external_runtime_signing_boundary",
        "secret_reference_mode": "external_runtime_reference_only",
        "secret_reference_placeholder": "OPERATOR_HELD_SIGNING_SECRET_REF",
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "secret_material_required_in_future_signing": True,
        "reads_secret_in_preview": False,
        "accepts_plaintext_secret": False,
        "permits_secret_value_logging": False,
        "ai_controlled_preflight_produces_nonsecret_envelope": True,
        "manual_review_mode": "exception_only",
    }
    command_preview = {
        "mode": "future_command_shape_only",
        "command_shape": (
            "sign-db-apply-authorization --request <final-signable-request-package> "
            "--secret-ref <operator-held-runtime-reference> --check-mode"
        ),
        "redacts_secret_values": True,
        "executes_in_preview": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
    }
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and final_package.get("secret_material_included") is False
        and final_package.get("secret_material_required_in_preview") is False
        and final_package.get("reads_secret_in_preview") is False
        and final_package.get("executes_shell_in_preview") is False
        and final_package.get("executes_sql_in_preview") is False
        and final_package.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signing_execution_preflight_check(
            "signing_issuer_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_READY"
            and issuer_closeout.get("ready_for_future_signing_issuer_closeout") is True
            and final_package.get("ready_for_future_final_signable_request_package") is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_signing_issuer_closeout": issuer_closeout.get(
                    "ready_for_future_signing_issuer_closeout"
                ),
                "ready_for_future_final_signable_request_package": final_package.get(
                    "ready_for_future_final_signable_request_package"
                ),
            },
            "wait_for_signing_issuer_closeout",
        ),
        _authorization_signing_execution_preflight_check(
            "final_signable_request_package_complete",
            final_package.get("authorization_material_type") == "final_signable_request_package"
            and bool(final_package.get("package_id"))
            and bool(final_package.get("source_signable_request_boundary_id"))
            and final_package.get("ready_for_database_apply_now") is False
            and final_package.get("issues_database_apply_authorization") is False
            and final_package.get("signs_database_apply_authorization") is False,
            {
                "package_id": final_package.get("package_id"),
                "authorization_material_type": final_package.get("authorization_material_type"),
                "source_signable_request_boundary_id": final_package.get(
                    "source_signable_request_boundary_id"
                ),
            },
            "wait_for_final_signable_request_package",
        ),
        _authorization_signing_execution_preflight_check(
            "source_chain_ids_present",
            bool(issuer_closeout.get("closeout_id"))
            and bool(final_package.get("source_signing_issuer_guard_id"))
            and bool(final_package.get("source_unsigned_signing_decision_package_id"))
            and bool(final_package.get("source_issuer_gate_id"))
            and bool(final_package.get("source_nonsecret_envelope_id"))
            and bool(final_package.get("source_lane_guard_id"))
            and bool(final_package.get("source_intake_id")),
            {
                "closeout_id": issuer_closeout.get("closeout_id"),
                "source_signing_issuer_guard_id": final_package.get(
                    "source_signing_issuer_guard_id"
                ),
                "source_unsigned_signing_decision_package_id": final_package.get(
                    "source_unsigned_signing_decision_package_id"
                ),
                "source_issuer_gate_id": final_package.get("source_issuer_gate_id"),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signing_execution_preflight_check(
            "same_run_production_truth_required",
            final_package.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": final_package.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signing_execution_preflight_check(
            "post_apply_verifier_required",
            final_package.get("requires_post_apply_verifier") is True
            and bool(final_package.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_post_apply_verifier": final_package.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": final_package.get(
                    "post_apply_verifier_endpoint"
                ),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier",
        ),
        _authorization_signing_execution_preflight_check(
            "migration_file_hash_locked",
            final_package.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and final_package.get("hash_matches") is True
            and bool(final_package.get("expected_sha256"))
            and final_package.get("expected_sha256") == final_package.get("actual_sha256"),
            {
                "target_file": final_package.get("target_file"),
                "hash_matches": final_package.get("hash_matches"),
                "expected_sha256": final_package.get("expected_sha256"),
                "actual_sha256": final_package.get("actual_sha256"),
            },
            "abort_on_migration_file_hash_mismatch",
        ),
        _authorization_signing_execution_preflight_check(
            "required_nonsecret_signing_inputs_complete",
            len(required_nonsecret_inputs) == 10
            and all(item.get("secret") is False for item in required_nonsecret_inputs)
            and all(item.get("value") for item in required_nonsecret_inputs),
            {
                "required_nonsecret_input_count": len(required_nonsecret_inputs),
                "secret_input_count": sum(1 for item in required_nonsecret_inputs if item.get("secret")),
            },
            "wait_for_nonsecret_signing_inputs",
        ),
        _authorization_signing_execution_preflight_check(
            "operator_held_secret_boundary_is_externalized",
            operator_held_secret_boundary_contract.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_held_secret_boundary_contract.get("secret_material_included") is False
            and operator_held_secret_boundary_contract.get("secret_material_required_in_preview")
            is False
            and operator_held_secret_boundary_contract.get("reads_secret_in_preview") is False
            and operator_held_secret_boundary_contract.get("accepts_plaintext_secret") is False
            and operator_held_secret_boundary_contract.get("permits_secret_value_logging") is False,
            {
                "secret_reference_mode": operator_held_secret_boundary_contract.get(
                    "secret_reference_mode"
                ),
                "secret_material_included": operator_held_secret_boundary_contract.get(
                    "secret_material_included"
                ),
                "reads_secret_in_preview": operator_held_secret_boundary_contract.get(
                    "reads_secret_in_preview"
                ),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signing_execution_preflight_check(
            "future_command_preview_is_non_executing_and_redacted",
            command_preview.get("mode") == "future_command_shape_only"
            and command_preview.get("redacts_secret_values") is True
            and command_preview.get("executes_in_preview") is False
            and command_preview.get("signs_database_apply_authorization") is False
            and command_preview.get("writes_database") is False,
            {
                "mode": command_preview.get("mode"),
                "redacts_secret_values": command_preview.get("redacts_secret_values"),
                "executes_in_preview": command_preview.get("executes_in_preview"),
            },
            "block_if_command_preview_executes_or_exposes_secret",
        ),
        _authorization_signing_execution_preflight_check(
            "rollback_and_abort_boundaries_present",
            len(rollback_boundary) == 4 and len(abort_conditions) == 8,
            {
                "rollback_boundary_count": len(rollback_boundary),
                "abort_condition_count": len(abort_conditions),
            },
            "wait_for_rollback_or_abort_boundary",
        ),
        _authorization_signing_execution_preflight_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free,
            {
                "writes_script_count": summary.get("writes_script_count", 0),
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
        _authorization_signing_execution_preflight_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and issuer_closeout.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": issuer_closeout.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    preflight_ready = not waiting_checks
    preflight_status = (
        "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT"
    )
    future_authorization_signing_execution_preflight = {
        "preflight_id": preflight_id,
        "source_signing_issuer_closeout_id": issuer_closeout.get("closeout_id"),
        "source_final_signable_request_package_id": final_package.get("package_id"),
        "status": preflight_status,
        "ready_for_future_signing_execution_preflight": preflight_ready,
        "can_enter_future_authorization_signing_execution_lane": preflight_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    signing_execution_preflight_package = {
        "package_id": preflight_id,
        "authorization_material_type": "signing_execution_preflight_package",
        "source_final_signable_request_package_id": final_package.get("package_id"),
        "source_signing_issuer_closeout_id": issuer_closeout.get("closeout_id"),
        "status": preflight_status,
        "ready_for_future_signing_execution_preflight": preflight_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "required_nonsecret_inputs": required_nonsecret_inputs,
        "required_nonsecret_input_count": len(required_nonsecret_inputs),
        "operator_held_secret_boundary_contract": operator_held_secret_boundary_contract,
        "command_preview": command_preview,
        "abort_conditions": abort_conditions,
        "rollback_boundary": rollback_boundary,
        "target_file": final_package.get("target_file"),
        "expected_sha256": final_package.get("expected_sha256"),
        "actual_sha256": final_package.get("actual_sha256"),
        "hash_matches": final_package.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": final_package.get("post_apply_verifier_endpoint"),
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    signing_execution_preflight_contract = {
        "mode": "explicit_authorization_signing_execution_preflight_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-preflight"
        ),
        "source_signing_issuer_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_explicit_authorization_signing_execution_lane": preflight_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_POLICY,
        "result": preflight_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_signing_execution_preflight_ready_count": (
                1 if preflight_ready else 0
            ),
            "signing_execution_preflight_check_count": len(checks),
            "signing_execution_preflight_pass_count": passed_count,
            "signing_execution_preflight_waiting_count": len(waiting_checks),
            "authorization_signing_issuer_closeout_ready_count": summary.get(
                "authorization_signing_issuer_closeout_ready_count", 0
            ),
            "signing_issuer_closeout_check_count": summary.get(
                "signing_issuer_closeout_check_count", 0
            ),
            "signing_issuer_closeout_pass_count": summary.get(
                "signing_issuer_closeout_pass_count", 0
            ),
            "final_signable_request_package_ready_count": (
                1
                if final_package.get("ready_for_future_final_signable_request_package") is True
                else 0
            ),
            "operator_held_secret_boundary_count": 1,
            "signing_execution_input_requirement_count": len(required_nonsecret_inputs),
            "signing_execution_abort_condition_count": len(abort_conditions),
            "rollback_boundary_count": len(rollback_boundary),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signing_execution_preflight": (
            future_authorization_signing_execution_preflight
        ),
        "signing_execution_preflight_package": signing_execution_preflight_package,
        "operator_held_secret_boundary_contract": operator_held_secret_boundary_contract,
        "signing_execution_preflight_contract": signing_execution_preflight_contract,
        "signing_execution_preflight_checks": checks,
        "source_signing_issuer_closeout_summary": summary,
        "source_signing_issuer_closeout_contract": closeout_contract,
        "source_final_signable_request_package": final_package,
        "safety": {
            "read_only_db_apply_authorization_signing_execution_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preflight to validate a future explicit authorization signing execution request.",
            "Keep secret values outside AI payloads; the preview only carries an external runtime reference placeholder.",
            "Require same-run production truth, hash lock, rollback boundary, and post-apply verifier before any future signing run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the future signing execution preflight without signing authorization."""
    preflight = build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_preflight = preflight.get("future_authorization_signing_execution_preflight") or {}
    package = preflight.get("signing_execution_preflight_package") or {}
    boundary = preflight.get("operator_held_secret_boundary_contract") or {}
    preflight_contract = preflight.get("signing_execution_preflight_contract") or {}
    summary = preflight.get("summary") or {}
    safety = preflight.get("safety") or {}
    required_inputs = list(package.get("required_nonsecret_inputs") or [])
    abort_conditions = list(package.get("abort_conditions") or [])
    rollback_boundary = list(package.get("rollback_boundary") or [])
    command_preview = package.get("command_preview") or {}
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and package.get("secret_material_included") is False
        and package.get("secret_material_required_in_preview") is False
        and package.get("reads_secret_in_preview") is False
        and package.get("executes_shell_in_preview") is False
        and package.get("executes_sql_in_preview") is False
        and package.get("writes_database_in_preview") is False
        and boundary.get("secret_material_included") is False
        and boundary.get("reads_secret_in_preview") is False
    )
    checks = [
        _authorization_signing_execution_closeout_check(
            "signing_execution_preflight_ready",
            preflight.get("result") == "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_READY"
            and future_preflight.get("ready_for_future_signing_execution_preflight") is True
            and package.get("ready_for_future_signing_execution_preflight") is True,
            {
                "result": preflight.get("result"),
                "ready_for_future_signing_execution_preflight": future_preflight.get(
                    "ready_for_future_signing_execution_preflight"
                ),
                "package_ready_for_future_signing_execution_preflight": package.get(
                    "ready_for_future_signing_execution_preflight"
                ),
            },
            "wait_for_signing_execution_preflight",
        ),
        _authorization_signing_execution_closeout_check(
            "unsigned_receipt_boundary_source_package_complete",
            package.get("authorization_material_type") == "signing_execution_preflight_package"
            and bool(package.get("package_id"))
            and bool(package.get("source_final_signable_request_package_id"))
            and bool(package.get("source_signing_issuer_closeout_id"))
            and package.get("ready_for_database_apply_now") is False
            and package.get("issues_database_apply_authorization") is False
            and package.get("signs_database_apply_authorization") is False,
            {
                "package_id": package.get("package_id"),
                "source_final_signable_request_package_id": package.get(
                    "source_final_signable_request_package_id"
                ),
                "source_signing_issuer_closeout_id": package.get(
                    "source_signing_issuer_closeout_id"
                ),
            },
            "wait_for_signing_execution_preflight_package",
        ),
        _authorization_signing_execution_closeout_check(
            "source_chain_ids_present",
            bool(future_preflight.get("preflight_id"))
            and bool(future_preflight.get("source_signing_issuer_closeout_id"))
            and bool(future_preflight.get("source_final_signable_request_package_id"))
            and bool(package.get("source_final_signable_request_package_id"))
            and bool(package.get("source_signing_issuer_closeout_id")),
            {
                "preflight_id": future_preflight.get("preflight_id"),
                "source_signing_issuer_closeout_id": future_preflight.get(
                    "source_signing_issuer_closeout_id"
                ),
                "source_final_signable_request_package_id": future_preflight.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signing_execution_closeout_check(
            "operator_held_secret_boundary_carried_forward",
            boundary.get("secret_reference_mode") == "external_runtime_reference_only"
            and boundary.get("secret_material_included") is False
            and boundary.get("secret_material_required_in_preview") is False
            and boundary.get("reads_secret_in_preview") is False
            and boundary.get("accepts_plaintext_secret") is False
            and boundary.get("permits_secret_value_logging") is False,
            {
                "secret_reference_mode": boundary.get("secret_reference_mode"),
                "secret_material_included": boundary.get("secret_material_included"),
                "reads_secret_in_preview": boundary.get("reads_secret_in_preview"),
                "accepts_plaintext_secret": boundary.get("accepts_plaintext_secret"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signing_execution_closeout_check(
            "required_nonsecret_inputs_carried_forward",
            int(summary.get("signing_execution_input_requirement_count") or 0) == 10
            and len(required_inputs) == 10
            and all(item.get("secret") is False for item in required_inputs)
            and all(item.get("value") for item in required_inputs),
            {
                "summary_input_count": summary.get("signing_execution_input_requirement_count", 0),
                "required_input_count": len(required_inputs),
                "secret_input_count": sum(1 for item in required_inputs if item.get("secret")),
            },
            "wait_for_nonsecret_signing_inputs",
        ),
        _authorization_signing_execution_closeout_check(
            "same_run_production_truth_required",
            package.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": package.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signing_execution_closeout_check(
            "post_apply_verifier_required",
            package.get("requires_post_apply_verifier") is True
            and bool(package.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_post_apply_verifier": package.get("requires_post_apply_verifier"),
                "post_apply_verifier_endpoint": package.get("post_apply_verifier_endpoint"),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier",
        ),
        _authorization_signing_execution_closeout_check(
            "migration_file_hash_locked",
            package.get("target_file") == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and package.get("hash_matches") is True
            and bool(package.get("expected_sha256"))
            and package.get("expected_sha256") == package.get("actual_sha256"),
            {
                "target_file": package.get("target_file"),
                "hash_matches": package.get("hash_matches"),
                "expected_sha256": package.get("expected_sha256"),
                "actual_sha256": package.get("actual_sha256"),
            },
            "abort_on_migration_file_hash_mismatch",
        ),
        _authorization_signing_execution_closeout_check(
            "future_command_preview_is_non_executing_and_redacted",
            command_preview.get("mode") == "future_command_shape_only"
            and command_preview.get("redacts_secret_values") is True
            and command_preview.get("executes_in_preview") is False
            and command_preview.get("signs_database_apply_authorization") is False
            and command_preview.get("writes_database") is False,
            {
                "mode": command_preview.get("mode"),
                "redacts_secret_values": command_preview.get("redacts_secret_values"),
                "executes_in_preview": command_preview.get("executes_in_preview"),
            },
            "block_if_command_preview_executes_or_exposes_secret",
        ),
        _authorization_signing_execution_closeout_check(
            "rollback_and_abort_boundaries_carried_forward",
            len(rollback_boundary) == 4
            and len(abort_conditions) == 8
            and int(summary.get("rollback_boundary_count") or 0) == 4
            and int(summary.get("signing_execution_abort_condition_count") or 0) == 8,
            {
                "rollback_boundary_count": len(rollback_boundary),
                "abort_condition_count": len(abort_conditions),
                "summary_rollback_boundary_count": summary.get("rollback_boundary_count", 0),
                "summary_abort_condition_count": summary.get(
                    "signing_execution_abort_condition_count", 0
                ),
            },
            "wait_for_rollback_or_abort_boundary",
        ),
        _authorization_signing_execution_closeout_check(
            "closeout_does_not_authorize_sign_or_apply",
            preflight_contract.get("permits_future_explicit_authorization_signing_execution_lane")
            is True
            and preflight_contract.get("issues_database_apply_authorization") is False
            and preflight_contract.get("ready_for_database_apply_now") is False
            and preflight_contract.get("signs_database_apply_authorization") is False
            and preflight_contract.get("writes_database") is False
            and preflight_contract.get("executes_in_preview") is False
            and future_preflight.get("issues_database_apply_authorization") is False
            and future_preflight.get("ready_for_database_apply_now") is False
            and future_preflight.get("signs_database_apply_authorization") is False,
            {
                "permits_future_explicit_authorization_signing_execution_lane": (
                    preflight_contract.get(
                        "permits_future_explicit_authorization_signing_execution_lane"
                    )
                ),
                "issues_database_apply_authorization": preflight_contract.get(
                    "issues_database_apply_authorization"
                ),
                "signs_database_apply_authorization": preflight_contract.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_closeout_authorizes_signs_or_applies",
        ),
        _authorization_signing_execution_closeout_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free,
            {
                "writes_script_count": summary.get("writes_script_count", 0),
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT"
    )
    closeout_id = _db_apply_authorization_signing_execution_closeout_id(preflight)
    future_authorization_signing_execution_closeout = {
        "closeout_id": closeout_id,
        "source_signing_execution_preflight_id": future_preflight.get("preflight_id"),
        "source_final_signable_request_package_id": future_preflight.get(
            "source_final_signable_request_package_id"
        ),
        "source_signing_issuer_closeout_id": future_preflight.get(
            "source_signing_issuer_closeout_id"
        ),
        "status": closeout_status,
        "ready_for_future_signing_execution_closeout": closeout_ready,
        "can_enter_future_unsigned_signed_authorization_receipt_boundary": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    unsigned_signed_authorization_receipt_boundary = {
        "boundary_id": closeout_id,
        "authorization_material_type": "unsigned_signed_authorization_receipt_boundary",
        "source_signing_execution_preflight_id": future_preflight.get("preflight_id"),
        "source_signing_execution_preflight_package_id": package.get("package_id"),
        "source_final_signable_request_package_id": package.get(
            "source_final_signable_request_package_id"
        ),
        "source_signing_issuer_closeout_id": package.get("source_signing_issuer_closeout_id"),
        "status": closeout_status,
        "ready_for_future_unsigned_signed_authorization_receipt_boundary": closeout_ready,
        "ready_for_future_signed_authorization_receipt_lane": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "required_nonsecret_inputs": required_inputs,
        "operator_held_secret_boundary_contract": boundary,
        "command_preview": command_preview,
        "abort_conditions": abort_conditions,
        "rollback_boundary": rollback_boundary,
        "target_file": package.get("target_file"),
        "expected_sha256": package.get("expected_sha256"),
        "actual_sha256": package.get("actual_sha256"),
        "hash_matches": package.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": package.get("post_apply_verifier_endpoint"),
    }
    signing_execution_closeout_contract = {
        "mode": "explicit_authorization_signing_execution_closeout_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-closeout"
        ),
        "source_signing_execution_preflight_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-preflight"
        ),
        "machine_verifiable": True,
        "permits_future_unsigned_signed_authorization_receipt_boundary": closeout_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(preflight.get("success")),
        "generated_at": preflight.get("generated_at"),
        "source_policy": preflight.get("policy"),
        "stats": preflight.get("stats") or {},
        "summary": {
            "authorization_signing_execution_closeout_ready_count": 1 if closeout_ready else 0,
            "signing_execution_closeout_check_count": len(checks),
            "signing_execution_closeout_pass_count": passed_count,
            "signing_execution_closeout_waiting_count": len(waiting_checks),
            "authorization_signing_execution_preflight_ready_count": summary.get(
                "authorization_signing_execution_preflight_ready_count", 0
            ),
            "signing_execution_preflight_check_count": summary.get(
                "signing_execution_preflight_check_count", 0
            ),
            "signing_execution_preflight_pass_count": summary.get(
                "signing_execution_preflight_pass_count", 0
            ),
            "unsigned_signed_authorization_receipt_boundary_count": 1,
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "signing_execution_input_requirement_count": summary.get(
                "signing_execution_input_requirement_count", 0
            ),
            "signing_execution_abort_condition_count": summary.get(
                "signing_execution_abort_condition_count", 0
            ),
            "rollback_boundary_count": summary.get("rollback_boundary_count", 0),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signing_execution_closeout": (
            future_authorization_signing_execution_closeout
        ),
        "unsigned_signed_authorization_receipt_boundary": (
            unsigned_signed_authorization_receipt_boundary
        ),
        "signing_execution_closeout_contract": signing_execution_closeout_contract,
        "signing_execution_closeout_checks": checks,
        "source_signing_execution_preflight_summary": summary,
        "source_signing_execution_preflight_contract": preflight_contract,
        "source_signing_execution_preflight_package": package,
        "safety": {
            "read_only_db_apply_authorization_signing_execution_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the unsigned receipt boundary for a future signed authorization receipt lane.",
            "Keep signing, secret reads, shell execution, SQL, and DB writes out of this closeout.",
            "Require same-run production truth, hash lock, rollback boundary, and post-apply verifier before any future signing receipt run.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Preflight a future externally signed authorization receipt without signing."""
    closeout = build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_closeout = closeout.get("future_authorization_signing_execution_closeout") or {}
    unsigned_boundary = closeout.get("unsigned_signed_authorization_receipt_boundary") or {}
    closeout_contract = closeout.get("signing_execution_closeout_contract") or {}
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    preflight_id = _db_apply_authorization_signed_receipt_preflight_id(closeout)
    required_inputs = list(unsigned_boundary.get("required_nonsecret_inputs") or [])
    abort_conditions = list(unsigned_boundary.get("abort_conditions") or [])
    rollback_boundary = list(unsigned_boundary.get("rollback_boundary") or [])
    operator_secret_boundary = (
        unsigned_boundary.get("operator_held_secret_boundary_contract") or {}
    )
    command_preview = unsigned_boundary.get("command_preview") or {}
    required_external_receipt_evidence = [
        "external_receipt_id",
        "source_unsigned_receipt_boundary_id",
        "source_signing_execution_closeout_id",
        "source_final_signable_request_package_id",
        "signer_key_id_reference",
        "signature_algorithm_reference",
        "signed_at_utc",
        "payload_sha256",
        "receipt_sha256",
        "detached_signature_verification_status",
    ]
    external_receipt_acceptance_gates = [
        "production_truth_matches_receipt_generation_run",
        "source_unsigned_boundary_id_matches",
        "payload_hash_matches_final_signable_request_package",
        "receipt_hash_is_present_and_nonempty",
        "detached_signature_verification_status_is_passed",
        "signer_key_id_is_reference_only",
        "no_secret_or_signature_material_in_ai_payload",
        "post_apply_verifier_still_required",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and unsigned_boundary.get("signed_authorization_receipt_included") is False
        and unsigned_boundary.get("signature_material_included") is False
        and unsigned_boundary.get("secret_material_included") is False
        and unsigned_boundary.get("secret_material_required_in_preview") is False
        and unsigned_boundary.get("reads_secret_in_preview") is False
        and unsigned_boundary.get("executes_shell_in_preview") is False
        and unsigned_boundary.get("executes_sql_in_preview") is False
        and unsigned_boundary.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signed_receipt_preflight_check(
            "signing_execution_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_READY"
            and future_closeout.get("ready_for_future_signing_execution_closeout") is True
            and unsigned_boundary.get(
                "ready_for_future_unsigned_signed_authorization_receipt_boundary"
            )
            is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_signing_execution_closeout": future_closeout.get(
                    "ready_for_future_signing_execution_closeout"
                ),
                "ready_for_future_unsigned_signed_authorization_receipt_boundary": (
                    unsigned_boundary.get(
                        "ready_for_future_unsigned_signed_authorization_receipt_boundary"
                    )
                ),
            },
            "wait_for_signing_execution_closeout",
        ),
        _authorization_signed_receipt_preflight_check(
            "unsigned_receipt_boundary_complete",
            unsigned_boundary.get("authorization_material_type")
            == "unsigned_signed_authorization_receipt_boundary"
            and bool(unsigned_boundary.get("boundary_id"))
            and bool(unsigned_boundary.get("source_signing_execution_preflight_id"))
            and bool(unsigned_boundary.get("source_final_signable_request_package_id"))
            and unsigned_boundary.get("ready_for_database_apply_now") is False
            and unsigned_boundary.get("issues_database_apply_authorization") is False
            and unsigned_boundary.get("signs_database_apply_authorization") is False,
            {
                "boundary_id": unsigned_boundary.get("boundary_id"),
                "authorization_material_type": unsigned_boundary.get(
                    "authorization_material_type"
                ),
                "source_final_signable_request_package_id": unsigned_boundary.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_unsigned_receipt_boundary",
        ),
        _authorization_signed_receipt_preflight_check(
            "source_chain_ids_present",
            bool(future_closeout.get("closeout_id"))
            and bool(future_closeout.get("source_signing_execution_preflight_id"))
            and bool(future_closeout.get("source_final_signable_request_package_id"))
            and bool(future_closeout.get("source_signing_issuer_closeout_id"))
            and bool(unsigned_boundary.get("source_signing_execution_preflight_package_id"))
            and bool(unsigned_boundary.get("source_signing_issuer_closeout_id")),
            {
                "closeout_id": future_closeout.get("closeout_id"),
                "source_signing_execution_preflight_id": future_closeout.get(
                    "source_signing_execution_preflight_id"
                ),
                "source_final_signable_request_package_id": future_closeout.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signed_receipt_preflight_check(
            "external_receipt_evidence_contract_complete",
            len(required_external_receipt_evidence) == 10
            and len(external_receipt_acceptance_gates) == 8,
            {
                "required_external_receipt_evidence_count": len(
                    required_external_receipt_evidence
                ),
                "external_receipt_acceptance_gate_count": len(
                    external_receipt_acceptance_gates
                ),
            },
            "wait_for_external_receipt_evidence_contract",
        ),
        _authorization_signed_receipt_preflight_check(
            "operator_held_secret_boundary_carried_forward",
            operator_secret_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_secret_boundary.get("secret_material_included") is False
            and operator_secret_boundary.get("secret_material_required_in_preview") is False
            and operator_secret_boundary.get("reads_secret_in_preview") is False
            and operator_secret_boundary.get("accepts_plaintext_secret") is False
            and operator_secret_boundary.get("permits_secret_value_logging") is False,
            {
                "secret_reference_mode": operator_secret_boundary.get("secret_reference_mode"),
                "secret_material_included": operator_secret_boundary.get(
                    "secret_material_included"
                ),
                "reads_secret_in_preview": operator_secret_boundary.get(
                    "reads_secret_in_preview"
                ),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signed_receipt_preflight_check(
            "same_run_production_truth_required",
            unsigned_boundary.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": unsigned_boundary.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signed_receipt_preflight_check(
            "post_apply_verifier_required",
            unsigned_boundary.get("requires_post_apply_verifier") is True
            and bool(unsigned_boundary.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_post_apply_verifier": unsigned_boundary.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": unsigned_boundary.get(
                    "post_apply_verifier_endpoint"
                ),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier",
        ),
        _authorization_signed_receipt_preflight_check(
            "migration_file_hash_locked",
            unsigned_boundary.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and unsigned_boundary.get("hash_matches") is True
            and bool(unsigned_boundary.get("expected_sha256"))
            and unsigned_boundary.get("expected_sha256") == unsigned_boundary.get("actual_sha256"),
            {
                "target_file": unsigned_boundary.get("target_file"),
                "hash_matches": unsigned_boundary.get("hash_matches"),
                "expected_sha256": unsigned_boundary.get("expected_sha256"),
                "actual_sha256": unsigned_boundary.get("actual_sha256"),
            },
            "abort_on_migration_file_hash_mismatch",
        ),
        _authorization_signed_receipt_preflight_check(
            "nonsecret_inputs_and_command_preview_carried_forward",
            int(summary.get("signing_execution_input_requirement_count") or 0) == 10
            and len(required_inputs) == 10
            and all(item.get("secret") is False for item in required_inputs)
            and command_preview.get("mode") == "future_command_shape_only"
            and command_preview.get("redacts_secret_values") is True
            and command_preview.get("executes_in_preview") is False
            and command_preview.get("signs_database_apply_authorization") is False,
            {
                "required_input_count": len(required_inputs),
                "command_preview_mode": command_preview.get("mode"),
                "redacts_secret_values": command_preview.get("redacts_secret_values"),
            },
            "wait_for_nonsecret_inputs_or_command_preview",
        ),
        _authorization_signed_receipt_preflight_check(
            "rollback_and_abort_boundaries_carried_forward",
            len(rollback_boundary) == 4
            and len(abort_conditions) == 8
            and int(summary.get("rollback_boundary_count") or 0) == 4
            and int(summary.get("signing_execution_abort_condition_count") or 0) == 8,
            {
                "rollback_boundary_count": len(rollback_boundary),
                "abort_condition_count": len(abort_conditions),
                "summary_rollback_boundary_count": summary.get("rollback_boundary_count", 0),
                "summary_abort_condition_count": summary.get(
                    "signing_execution_abort_condition_count", 0
                ),
            },
            "wait_for_rollback_or_abort_boundary",
        ),
        _authorization_signed_receipt_preflight_check(
            "preflight_has_no_signed_receipt_signature_or_authorization",
            unsigned_boundary.get("signed_authorization_receipt_included") is False
            and unsigned_boundary.get("signature_material_included") is False
            and unsigned_boundary.get("secret_material_included") is False
            and closeout_contract.get(
                "permits_future_unsigned_signed_authorization_receipt_boundary"
            )
            is True
            and closeout_contract.get("issues_database_apply_authorization") is False
            and closeout_contract.get("ready_for_database_apply_now") is False
            and closeout_contract.get("signs_database_apply_authorization") is False,
            {
                "signed_authorization_receipt_included": unsigned_boundary.get(
                    "signed_authorization_receipt_included"
                ),
                "signature_material_included": unsigned_boundary.get(
                    "signature_material_included"
                ),
                "signs_database_apply_authorization": closeout_contract.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_signed_receipt_or_authorization_is_present",
        ),
        _authorization_signed_receipt_preflight_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free,
            {
                "writes_script_count": summary.get("writes_script_count", 0),
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    preflight_ready = not waiting_checks
    preflight_status = (
        "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT"
    )
    future_authorization_signed_receipt_preflight = {
        "preflight_id": preflight_id,
        "source_signing_execution_closeout_id": future_closeout.get("closeout_id"),
        "source_unsigned_receipt_boundary_id": unsigned_boundary.get("boundary_id"),
        "source_final_signable_request_package_id": unsigned_boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": preflight_status,
        "ready_for_future_signed_authorization_receipt_preflight": preflight_ready,
        "can_enter_future_external_signing_receipt_evidence_boundary": preflight_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    external_signing_receipt_evidence_boundary = {
        "boundary_id": preflight_id,
        "authorization_material_type": "external_signing_receipt_evidence_boundary",
        "source_signing_execution_closeout_id": future_closeout.get("closeout_id"),
        "source_unsigned_receipt_boundary_id": unsigned_boundary.get("boundary_id"),
        "source_signing_execution_preflight_id": unsigned_boundary.get(
            "source_signing_execution_preflight_id"
        ),
        "source_final_signable_request_package_id": unsigned_boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": preflight_status,
        "ready_for_future_external_signing_receipt_evidence_boundary": preflight_ready,
        "ready_for_future_signed_authorization_receipt_lane": preflight_ready,
        "required_external_receipt_evidence": required_external_receipt_evidence,
        "required_external_receipt_evidence_count": len(required_external_receipt_evidence),
        "external_receipt_acceptance_gates": external_receipt_acceptance_gates,
        "external_receipt_acceptance_gate_count": len(external_receipt_acceptance_gates),
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "operator_held_secret_boundary_contract": operator_secret_boundary,
        "target_file": unsigned_boundary.get("target_file"),
        "expected_sha256": unsigned_boundary.get("expected_sha256"),
        "actual_sha256": unsigned_boundary.get("actual_sha256"),
        "hash_matches": unsigned_boundary.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": unsigned_boundary.get("post_apply_verifier_endpoint"),
    }
    signed_receipt_preflight_contract = {
        "mode": "signed_authorization_receipt_preflight_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-preflight"
        ),
        "source_signing_execution_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_external_signing_receipt_evidence_boundary": preflight_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_POLICY,
        "result": preflight_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_signed_receipt_preflight_ready_count": 1 if preflight_ready else 0,
            "signed_receipt_preflight_check_count": len(checks),
            "signed_receipt_preflight_pass_count": passed_count,
            "signed_receipt_preflight_waiting_count": len(waiting_checks),
            "authorization_signing_execution_closeout_ready_count": summary.get(
                "authorization_signing_execution_closeout_ready_count", 0
            ),
            "signing_execution_closeout_check_count": summary.get(
                "signing_execution_closeout_check_count", 0
            ),
            "unsigned_signed_authorization_receipt_boundary_count": summary.get(
                "unsigned_signed_authorization_receipt_boundary_count", 0
            ),
            "external_signing_receipt_evidence_boundary_count": 1,
            "required_external_receipt_evidence_count": len(required_external_receipt_evidence),
            "external_receipt_acceptance_gate_count": len(external_receipt_acceptance_gates),
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "signing_execution_input_requirement_count": summary.get(
                "signing_execution_input_requirement_count", 0
            ),
            "signing_execution_abort_condition_count": summary.get(
                "signing_execution_abort_condition_count", 0
            ),
            "rollback_boundary_count": summary.get("rollback_boundary_count", 0),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signed_receipt_preflight": (
            future_authorization_signed_receipt_preflight
        ),
        "external_signing_receipt_evidence_boundary": (
            external_signing_receipt_evidence_boundary
        ),
        "signed_receipt_preflight_contract": signed_receipt_preflight_contract,
        "signed_receipt_preflight_checks": checks,
        "source_signing_execution_closeout_summary": summary,
        "source_signing_execution_closeout_contract": closeout_contract,
        "source_unsigned_signed_authorization_receipt_boundary": unsigned_boundary,
        "safety": {
            "read_only_db_apply_authorization_signed_receipt_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preflight to validate future external signed authorization receipt evidence.",
            "Keep signed receipt content, signature material, secret values, shell execution, SQL, and DB writes out of this preflight.",
            "Require detached receipt verification, same-run production truth, hash lock, rollback boundary, and post-apply verifier before any future receipt closeout.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out future signed receipt preflight without carrying signed material."""
    preflight = build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_preflight = preflight.get("future_authorization_signed_receipt_preflight") or {}
    evidence_boundary = preflight.get("external_signing_receipt_evidence_boundary") or {}
    preflight_contract = preflight.get("signed_receipt_preflight_contract") or {}
    summary = preflight.get("summary") or {}
    safety = preflight.get("safety") or {}
    closeout_id = _db_apply_authorization_signed_receipt_closeout_id(preflight)
    required_evidence = list(evidence_boundary.get("required_external_receipt_evidence") or [])
    acceptance_gates = list(evidence_boundary.get("external_receipt_acceptance_gates") or [])
    operator_secret_boundary = (
        evidence_boundary.get("operator_held_secret_boundary_contract") or {}
    )
    detached_verification_checks = [
        "receipt_id_present",
        "source_unsigned_receipt_boundary_id_matches",
        "source_signing_execution_closeout_id_matches",
        "payload_sha256_matches_final_signable_request_package",
        "receipt_sha256_present",
        "signer_key_id_is_reference_only",
        "signature_algorithm_is_reference_only",
        "detached_signature_verification_status_passed",
        "same_run_production_truth_verified",
        "no_secret_or_signature_material_in_ai_payload",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and evidence_boundary.get("external_signed_authorization_receipt_included") is False
        and evidence_boundary.get("signed_authorization_receipt_included") is False
        and evidence_boundary.get("signature_material_included") is False
        and evidence_boundary.get("secret_material_included") is False
        and evidence_boundary.get("secret_material_required_in_preview") is False
        and evidence_boundary.get("reads_secret_in_preview") is False
        and evidence_boundary.get("executes_shell_in_preview") is False
        and evidence_boundary.get("executes_sql_in_preview") is False
        and evidence_boundary.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signed_receipt_closeout_check(
            "signed_receipt_preflight_ready",
            preflight.get("result") == "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_READY"
            and future_preflight.get("ready_for_future_signed_authorization_receipt_preflight")
            is True
            and evidence_boundary.get(
                "ready_for_future_external_signing_receipt_evidence_boundary"
            )
            is True,
            {
                "result": preflight.get("result"),
                "ready_for_future_signed_authorization_receipt_preflight": (
                    future_preflight.get(
                        "ready_for_future_signed_authorization_receipt_preflight"
                    )
                ),
                "ready_for_future_external_signing_receipt_evidence_boundary": (
                    evidence_boundary.get(
                        "ready_for_future_external_signing_receipt_evidence_boundary"
                    )
                ),
            },
            "wait_for_signed_receipt_preflight",
        ),
        _authorization_signed_receipt_closeout_check(
            "external_receipt_evidence_boundary_complete",
            evidence_boundary.get("authorization_material_type")
            == "external_signing_receipt_evidence_boundary"
            and bool(evidence_boundary.get("boundary_id"))
            and bool(evidence_boundary.get("source_signing_execution_closeout_id"))
            and bool(evidence_boundary.get("source_unsigned_receipt_boundary_id"))
            and bool(evidence_boundary.get("source_final_signable_request_package_id"))
            and evidence_boundary.get("ready_for_database_apply_now") is False
            and evidence_boundary.get("issues_database_apply_authorization") is False
            and evidence_boundary.get("signs_database_apply_authorization") is False,
            {
                "boundary_id": evidence_boundary.get("boundary_id"),
                "authorization_material_type": evidence_boundary.get("authorization_material_type"),
                "source_unsigned_receipt_boundary_id": evidence_boundary.get(
                    "source_unsigned_receipt_boundary_id"
                ),
            },
            "wait_for_external_receipt_evidence_boundary",
        ),
        _authorization_signed_receipt_closeout_check(
            "source_chain_ids_present",
            bool(future_preflight.get("preflight_id"))
            and bool(future_preflight.get("source_signing_execution_closeout_id"))
            and bool(future_preflight.get("source_unsigned_receipt_boundary_id"))
            and bool(future_preflight.get("source_final_signable_request_package_id"))
            and bool(evidence_boundary.get("source_signing_execution_preflight_id")),
            {
                "preflight_id": future_preflight.get("preflight_id"),
                "source_signing_execution_closeout_id": future_preflight.get(
                    "source_signing_execution_closeout_id"
                ),
                "source_unsigned_receipt_boundary_id": future_preflight.get(
                    "source_unsigned_receipt_boundary_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signed_receipt_closeout_check(
            "external_receipt_evidence_contract_carried_forward",
            len(required_evidence) == 10
            and len(acceptance_gates) == 8
            and int(summary.get("required_external_receipt_evidence_count") or 0) == 10
            and int(summary.get("external_receipt_acceptance_gate_count") or 0) == 8,
            {
                "required_external_receipt_evidence_count": len(required_evidence),
                "external_receipt_acceptance_gate_count": len(acceptance_gates),
                "summary_required_external_receipt_evidence_count": summary.get(
                    "required_external_receipt_evidence_count", 0
                ),
                "summary_external_receipt_acceptance_gate_count": summary.get(
                    "external_receipt_acceptance_gate_count", 0
                ),
            },
            "wait_for_external_receipt_evidence_contract",
        ),
        _authorization_signed_receipt_closeout_check(
            "detached_receipt_verification_boundary_contract_complete",
            len(detached_verification_checks) == 10
            and "detached_signature_verification_status_passed" in detached_verification_checks,
            {
                "detached_receipt_verification_check_count": len(
                    detached_verification_checks
                ),
                "requires_detached_signature_verification": (
                    "detached_signature_verification_status_passed"
                    in detached_verification_checks
                ),
            },
            "wait_for_detached_receipt_verification_contract",
        ),
        _authorization_signed_receipt_closeout_check(
            "operator_held_secret_boundary_carried_forward",
            operator_secret_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_secret_boundary.get("secret_material_included") is False
            and operator_secret_boundary.get("secret_material_required_in_preview") is False
            and operator_secret_boundary.get("reads_secret_in_preview") is False
            and operator_secret_boundary.get("accepts_plaintext_secret") is False
            and operator_secret_boundary.get("permits_secret_value_logging") is False,
            {
                "secret_reference_mode": operator_secret_boundary.get("secret_reference_mode"),
                "secret_material_included": operator_secret_boundary.get(
                    "secret_material_included"
                ),
                "reads_secret_in_preview": operator_secret_boundary.get(
                    "reads_secret_in_preview"
                ),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_signed_receipt_closeout_check(
            "same_run_production_truth_required",
            evidence_boundary.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": evidence_boundary.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signed_receipt_closeout_check(
            "post_apply_verifier_required",
            evidence_boundary.get("requires_post_apply_verifier") is True
            and bool(evidence_boundary.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_post_apply_verifier": evidence_boundary.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": evidence_boundary.get(
                    "post_apply_verifier_endpoint"
                ),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier",
        ),
        _authorization_signed_receipt_closeout_check(
            "migration_file_hash_locked",
            evidence_boundary.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and evidence_boundary.get("hash_matches") is True
            and bool(evidence_boundary.get("expected_sha256"))
            and evidence_boundary.get("expected_sha256") == evidence_boundary.get("actual_sha256"),
            {
                "target_file": evidence_boundary.get("target_file"),
                "hash_matches": evidence_boundary.get("hash_matches"),
                "expected_sha256": evidence_boundary.get("expected_sha256"),
                "actual_sha256": evidence_boundary.get("actual_sha256"),
            },
            "abort_on_migration_file_hash_mismatch",
        ),
        _authorization_signed_receipt_closeout_check(
            "closeout_has_no_signed_receipt_signature_or_authorization",
            evidence_boundary.get("external_signed_authorization_receipt_included") is False
            and evidence_boundary.get("signed_authorization_receipt_included") is False
            and evidence_boundary.get("signature_material_included") is False
            and evidence_boundary.get("secret_material_included") is False
            and preflight_contract.get(
                "permits_future_external_signing_receipt_evidence_boundary"
            )
            is True
            and preflight_contract.get("issues_database_apply_authorization") is False
            and preflight_contract.get("ready_for_database_apply_now") is False
            and preflight_contract.get("signs_database_apply_authorization") is False,
            {
                "external_signed_authorization_receipt_included": evidence_boundary.get(
                    "external_signed_authorization_receipt_included"
                ),
                "signed_authorization_receipt_included": evidence_boundary.get(
                    "signed_authorization_receipt_included"
                ),
                "signature_material_included": evidence_boundary.get(
                    "signature_material_included"
                ),
                "signs_database_apply_authorization": preflight_contract.get(
                    "signs_database_apply_authorization"
                ),
            },
            "block_if_signed_receipt_signature_or_authorization_is_present",
        ),
        _authorization_signed_receipt_closeout_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free,
            {
                "writes_script_count": summary.get("writes_script_count", 0),
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
        _authorization_signed_receipt_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_preflight.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": future_preflight.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT"
    )
    future_authorization_signed_receipt_closeout = {
        "closeout_id": closeout_id,
        "source_signed_receipt_preflight_id": future_preflight.get("preflight_id"),
        "source_external_receipt_evidence_boundary_id": evidence_boundary.get("boundary_id"),
        "source_signing_execution_closeout_id": future_preflight.get(
            "source_signing_execution_closeout_id"
        ),
        "source_unsigned_receipt_boundary_id": future_preflight.get(
            "source_unsigned_receipt_boundary_id"
        ),
        "source_final_signable_request_package_id": future_preflight.get(
            "source_final_signable_request_package_id"
        ),
        "status": closeout_status,
        "ready_for_future_signed_authorization_receipt_closeout": closeout_ready,
        "can_enter_future_detached_receipt_verification_boundary": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    detached_receipt_verification_boundary = {
        "boundary_id": closeout_id,
        "authorization_material_type": "detached_receipt_verification_boundary",
        "source_signed_receipt_preflight_id": future_preflight.get("preflight_id"),
        "source_external_receipt_evidence_boundary_id": evidence_boundary.get("boundary_id"),
        "source_signing_execution_closeout_id": evidence_boundary.get(
            "source_signing_execution_closeout_id"
        ),
        "source_unsigned_receipt_boundary_id": evidence_boundary.get(
            "source_unsigned_receipt_boundary_id"
        ),
        "source_final_signable_request_package_id": evidence_boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": closeout_status,
        "ready_for_future_detached_receipt_verification_boundary": closeout_ready,
        "ready_for_future_signed_authorization_receipt_verification_lane": closeout_ready,
        "required_external_receipt_evidence": required_evidence,
        "required_external_receipt_evidence_count": len(required_evidence),
        "external_receipt_acceptance_gates": acceptance_gates,
        "external_receipt_acceptance_gate_count": len(acceptance_gates),
        "detached_receipt_verification_checks": detached_verification_checks,
        "detached_receipt_verification_check_count": len(detached_verification_checks),
        "requires_detached_signature_verification": True,
        "detached_signature_verification_performed": False,
        "detached_signature_verification_status_required_in_future": True,
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "operator_held_secret_boundary_contract": operator_secret_boundary,
        "target_file": evidence_boundary.get("target_file"),
        "expected_sha256": evidence_boundary.get("expected_sha256"),
        "actual_sha256": evidence_boundary.get("actual_sha256"),
        "hash_matches": evidence_boundary.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": evidence_boundary.get("post_apply_verifier_endpoint"),
    }
    signed_receipt_closeout_contract = {
        "mode": "signed_authorization_receipt_closeout_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-closeout"
        ),
        "source_signed_receipt_preflight_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-preflight"
        ),
        "machine_verifiable": True,
        "permits_future_detached_receipt_verification_boundary": closeout_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(preflight.get("success")),
        "generated_at": preflight.get("generated_at"),
        "source_policy": preflight.get("policy"),
        "stats": preflight.get("stats") or {},
        "summary": {
            "authorization_signed_receipt_closeout_ready_count": 1 if closeout_ready else 0,
            "signed_receipt_closeout_check_count": len(checks),
            "signed_receipt_closeout_pass_count": passed_count,
            "signed_receipt_closeout_waiting_count": len(waiting_checks),
            "authorization_signed_receipt_preflight_ready_count": summary.get(
                "authorization_signed_receipt_preflight_ready_count", 0
            ),
            "signed_receipt_preflight_check_count": summary.get(
                "signed_receipt_preflight_check_count", 0
            ),
            "external_signing_receipt_evidence_boundary_count": summary.get(
                "external_signing_receipt_evidence_boundary_count", 0
            ),
            "detached_receipt_verification_boundary_count": 1,
            "required_external_receipt_evidence_count": summary.get(
                "required_external_receipt_evidence_count", 0
            ),
            "external_receipt_acceptance_gate_count": summary.get(
                "external_receipt_acceptance_gate_count", 0
            ),
            "detached_receipt_verification_check_count": len(detached_verification_checks),
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "signing_execution_input_requirement_count": summary.get(
                "signing_execution_input_requirement_count", 0
            ),
            "signing_execution_abort_condition_count": summary.get(
                "signing_execution_abort_condition_count", 0
            ),
            "rollback_boundary_count": summary.get("rollback_boundary_count", 0),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_signed_receipt_closeout": (
            future_authorization_signed_receipt_closeout
        ),
        "detached_receipt_verification_boundary": detached_receipt_verification_boundary,
        "signed_receipt_closeout_contract": signed_receipt_closeout_contract,
        "signed_receipt_closeout_checks": checks,
        "source_signed_receipt_preflight_summary": summary,
        "source_signed_receipt_preflight_contract": preflight_contract,
        "source_external_signing_receipt_evidence_boundary": evidence_boundary,
        "safety": {
            "read_only_db_apply_authorization_signed_receipt_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the detached receipt verification boundary for a future signed authorization receipt evidence lane.",
            "Keep signed receipt content, signature material, secret values, shell execution, SQL, and DB writes out of this closeout.",
            "Require real detached verification evidence in a future separate lane before any database apply authorization can be considered.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Define the future signed receipt evidence intake schema without taking secrets."""
    closeout = build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_closeout = closeout.get("future_authorization_signed_receipt_closeout") or {}
    detached_boundary = closeout.get("detached_receipt_verification_boundary") or {}
    closeout_contract = closeout.get("signed_receipt_closeout_contract") or {}
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    intake_id = _db_apply_authorization_signed_receipt_evidence_intake_id(closeout)
    required_external_evidence = list(
        detached_boundary.get("required_external_receipt_evidence") or []
    )
    external_acceptance_gates = list(
        detached_boundary.get("external_receipt_acceptance_gates") or []
    )
    detached_checks = list(
        detached_boundary.get("detached_receipt_verification_checks") or []
    )
    operator_secret_boundary = (
        detached_boundary.get("operator_held_secret_boundary_contract") or {}
    )
    detached_verification_evidence_fields = [
        "external_receipt_id",
        "source_signed_receipt_preflight_id",
        "source_external_receipt_evidence_boundary_id",
        "source_signed_receipt_closeout_id",
        "source_detached_receipt_verification_boundary_id",
        "payload_sha256",
        "receipt_sha256",
        "signer_key_id_reference",
        "signature_algorithm_reference",
        "detached_signature_verification_status",
        "verified_at_utc",
        "verifier_receipt_sha256",
    ]
    detached_verification_acceptance_gates = [
        "production_truth_matches_intake_run",
        "source_detached_boundary_id_matches",
        "source_external_receipt_evidence_boundary_id_matches",
        "source_signed_receipt_preflight_id_matches",
        "payload_hash_matches_final_signable_request_package",
        "receipt_hash_is_present_and_nonempty",
        "signer_key_id_is_reference_only",
        "signature_algorithm_is_reference_only",
        "detached_signature_verification_status_is_passed",
        "no_secret_signature_or_signed_receipt_body_in_ai_payload",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and detached_boundary.get("detached_signature_verification_performed") is False
        and detached_boundary.get("external_signed_authorization_receipt_included") is False
        and detached_boundary.get("signed_authorization_receipt_included") is False
        and detached_boundary.get("signature_material_included") is False
        and detached_boundary.get("secret_material_included") is False
        and detached_boundary.get("secret_material_required_in_preview") is False
        and detached_boundary.get("reads_secret_in_preview") is False
        and detached_boundary.get("executes_shell_in_preview") is False
        and detached_boundary.get("executes_sql_in_preview") is False
        and detached_boundary.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_signed_receipt_evidence_intake_check(
            "signed_receipt_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_READY"
            and future_closeout.get("ready_for_future_signed_authorization_receipt_closeout")
            is True
            and detached_boundary.get("ready_for_future_detached_receipt_verification_boundary")
            is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_signed_authorization_receipt_closeout": (
                    future_closeout.get(
                        "ready_for_future_signed_authorization_receipt_closeout"
                    )
                ),
                "ready_for_future_detached_receipt_verification_boundary": (
                    detached_boundary.get(
                        "ready_for_future_detached_receipt_verification_boundary"
                    )
                ),
            },
            "wait_for_signed_receipt_closeout",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "detached_receipt_verification_boundary_complete",
            detached_boundary.get("authorization_material_type")
            == "detached_receipt_verification_boundary"
            and bool(detached_boundary.get("boundary_id"))
            and bool(detached_boundary.get("source_signed_receipt_preflight_id"))
            and bool(detached_boundary.get("source_external_receipt_evidence_boundary_id"))
            and detached_boundary.get("ready_for_database_apply_now") is False
            and detached_boundary.get("issues_database_apply_authorization") is False
            and detached_boundary.get("signs_database_apply_authorization") is False,
            {
                "boundary_id": detached_boundary.get("boundary_id"),
                "authorization_material_type": detached_boundary.get(
                    "authorization_material_type"
                ),
                "source_external_receipt_evidence_boundary_id": detached_boundary.get(
                    "source_external_receipt_evidence_boundary_id"
                ),
            },
            "wait_for_detached_receipt_verification_boundary",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "source_chain_ids_present",
            bool(future_closeout.get("closeout_id"))
            and bool(future_closeout.get("source_signed_receipt_preflight_id"))
            and bool(future_closeout.get("source_external_receipt_evidence_boundary_id"))
            and bool(future_closeout.get("source_signing_execution_closeout_id"))
            and bool(detached_boundary.get("source_final_signable_request_package_id")),
            {
                "closeout_id": future_closeout.get("closeout_id"),
                "source_signed_receipt_preflight_id": future_closeout.get(
                    "source_signed_receipt_preflight_id"
                ),
                "source_final_signable_request_package_id": detached_boundary.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "external_receipt_contract_carried_forward",
            len(required_external_evidence) == 10
            and len(external_acceptance_gates) == 8
            and int(summary.get("required_external_receipt_evidence_count") or 0) == 10
            and int(summary.get("external_receipt_acceptance_gate_count") or 0) == 8,
            {
                "required_external_receipt_evidence_count": len(required_external_evidence),
                "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
                "summary_required_external_receipt_evidence_count": summary.get(
                    "required_external_receipt_evidence_count", 0
                ),
                "summary_external_receipt_acceptance_gate_count": summary.get(
                    "external_receipt_acceptance_gate_count", 0
                ),
            },
            "wait_for_external_receipt_contract",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "detached_verification_evidence_schema_complete",
            len(detached_verification_evidence_fields) == 12
            and len(detached_verification_acceptance_gates) == 10
            and len(detached_checks) == 10
            and "detached_signature_verification_status_passed" in detached_checks,
            {
                "detached_verification_evidence_field_count": len(
                    detached_verification_evidence_fields
                ),
                "detached_verification_acceptance_gate_count": len(
                    detached_verification_acceptance_gates
                ),
                "source_detached_check_count": len(detached_checks),
            },
            "wait_for_detached_verification_evidence_schema",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "signer_and_algorithm_references_only",
            detached_boundary.get("signer_key_id_reference_only") is True
            and detached_boundary.get("signature_algorithm_reference_only") is True
            and "signer_key_id_reference" in detached_verification_evidence_fields
            and "signature_algorithm_reference" in detached_verification_evidence_fields,
            {
                "signer_key_id_reference_only": detached_boundary.get(
                    "signer_key_id_reference_only"
                ),
                "signature_algorithm_reference_only": detached_boundary.get(
                    "signature_algorithm_reference_only"
                ),
            },
            "abort_on_plaintext_key_or_algorithm_material",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "no_signed_receipt_signature_secret_or_verification_execution",
            detached_boundary.get("detached_signature_verification_performed") is False
            and detached_boundary.get("external_signed_authorization_receipt_included")
            is False
            and detached_boundary.get("signed_authorization_receipt_included") is False
            and detached_boundary.get("signature_material_included") is False
            and detached_boundary.get("secret_material_included") is False
            and operator_secret_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_secret_boundary.get("accepts_plaintext_secret") is False,
            {
                "detached_signature_verification_performed": detached_boundary.get(
                    "detached_signature_verification_performed"
                ),
                "external_signed_authorization_receipt_included": detached_boundary.get(
                    "external_signed_authorization_receipt_included"
                ),
                "signature_material_included": detached_boundary.get(
                    "signature_material_included"
                ),
                "secret_reference_mode": operator_secret_boundary.get(
                    "secret_reference_mode"
                ),
            },
            "abort_on_signed_receipt_signature_secret_or_verification_execution",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "same_run_production_truth_required",
            detached_boundary.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": detached_boundary.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "post_apply_verifier_required",
            detached_boundary.get("requires_post_apply_verifier") is True
            and bool(detached_boundary.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_post_apply_verifier": detached_boundary.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": detached_boundary.get(
                    "post_apply_verifier_endpoint"
                ),
                "post_apply_verifier_required_count": summary.get(
                    "post_apply_verifier_required_count", 0
                ),
            },
            "require_post_apply_verifier",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "migration_file_hash_locked",
            detached_boundary.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and detached_boundary.get("hash_matches") is True
            and bool(detached_boundary.get("expected_sha256"))
            and detached_boundary.get("expected_sha256")
            == detached_boundary.get("actual_sha256"),
            {
                "target_file": detached_boundary.get("target_file"),
                "hash_matches": detached_boundary.get("hash_matches"),
                "expected_sha256": detached_boundary.get("expected_sha256"),
                "actual_sha256": detached_boundary.get("actual_sha256"),
            },
            "abort_on_migration_file_hash_mismatch",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "preview_has_no_side_effects_and_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_or_signing",
        ),
        _authorization_signed_receipt_evidence_intake_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_closeout.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": future_closeout.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    intake_ready = not waiting_checks
    intake_status = (
        "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_READY"
        if intake_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT"
    )
    future_signed_authorization_receipt_evidence_intake = {
        "intake_id": intake_id,
        "source_signed_receipt_closeout_id": future_closeout.get("closeout_id"),
        "source_detached_receipt_verification_boundary_id": detached_boundary.get(
            "boundary_id"
        ),
        "source_signed_receipt_preflight_id": detached_boundary.get(
            "source_signed_receipt_preflight_id"
        ),
        "source_external_receipt_evidence_boundary_id": detached_boundary.get(
            "source_external_receipt_evidence_boundary_id"
        ),
        "source_final_signable_request_package_id": detached_boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": intake_status,
        "ready_for_future_signed_authorization_receipt_evidence_intake": intake_ready,
        "can_enter_future_detached_verification_evidence_validation": intake_ready,
        "external_signed_authorization_receipt_evidence_schema_ready": intake_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "detached_signature_verification_performed": False,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    detached_verification_evidence_schema = {
        "schema_id": intake_id,
        "authorization_material_type": "detached_verification_evidence_schema",
        "source_signed_receipt_closeout_id": future_closeout.get("closeout_id"),
        "source_detached_receipt_verification_boundary_id": detached_boundary.get(
            "boundary_id"
        ),
        "source_signed_receipt_preflight_id": detached_boundary.get(
            "source_signed_receipt_preflight_id"
        ),
        "source_external_receipt_evidence_boundary_id": detached_boundary.get(
            "source_external_receipt_evidence_boundary_id"
        ),
        "source_final_signable_request_package_id": detached_boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": intake_status,
        "ready_for_future_detached_verification_evidence_schema": intake_ready,
        "required_external_receipt_evidence": required_external_evidence,
        "required_external_receipt_evidence_count": len(required_external_evidence),
        "external_receipt_acceptance_gates": external_acceptance_gates,
        "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
        "detached_receipt_verification_checks": detached_checks,
        "detached_receipt_verification_check_count": len(detached_checks),
        "detached_verification_evidence_fields": detached_verification_evidence_fields,
        "detached_verification_evidence_field_count": len(
            detached_verification_evidence_fields
        ),
        "detached_verification_acceptance_gates": detached_verification_acceptance_gates,
        "detached_verification_acceptance_gate_count": len(
            detached_verification_acceptance_gates
        ),
        "requires_detached_signature_verification": True,
        "detached_signature_verification_performed": False,
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "operator_held_secret_boundary_contract": operator_secret_boundary,
        "target_file": detached_boundary.get("target_file"),
        "expected_sha256": detached_boundary.get("expected_sha256"),
        "actual_sha256": detached_boundary.get("actual_sha256"),
        "hash_matches": detached_boundary.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": detached_boundary.get(
            "post_apply_verifier_endpoint"
        ),
    }
    signed_receipt_evidence_intake_contract = {
        "mode": "signed_authorization_receipt_evidence_intake_schema_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-evidence-intake"
        ),
        "source_signed_receipt_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_detached_verification_evidence_validation": intake_ready,
        "accepts_plaintext_secret": False,
        "detached_signature_verification_performed": False,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_POLICY,
        "result": intake_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_signed_receipt_evidence_intake_ready_count": (
                1 if intake_ready else 0
            ),
            "signed_receipt_evidence_intake_check_count": len(checks),
            "signed_receipt_evidence_intake_pass_count": passed_count,
            "signed_receipt_evidence_intake_waiting_count": len(waiting_checks),
            "authorization_signed_receipt_closeout_ready_count": summary.get(
                "authorization_signed_receipt_closeout_ready_count", 0
            ),
            "signed_receipt_closeout_check_count": summary.get(
                "signed_receipt_closeout_check_count", 0
            ),
            "authorization_signed_receipt_preflight_ready_count": summary.get(
                "authorization_signed_receipt_preflight_ready_count", 0
            ),
            "signed_receipt_preflight_check_count": summary.get(
                "signed_receipt_preflight_check_count", 0
            ),
            "external_signing_receipt_evidence_boundary_count": summary.get(
                "external_signing_receipt_evidence_boundary_count", 0
            ),
            "detached_receipt_verification_boundary_count": summary.get(
                "detached_receipt_verification_boundary_count", 0
            ),
            "detached_verification_evidence_schema_count": 1,
            "required_external_receipt_evidence_count": summary.get(
                "required_external_receipt_evidence_count", 0
            ),
            "external_receipt_acceptance_gate_count": summary.get(
                "external_receipt_acceptance_gate_count", 0
            ),
            "detached_receipt_verification_check_count": summary.get(
                "detached_receipt_verification_check_count", 0
            ),
            "detached_verification_evidence_field_count": len(
                detached_verification_evidence_fields
            ),
            "detached_verification_acceptance_gate_count": len(
                detached_verification_acceptance_gates
            ),
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "rollback_boundary_count": summary.get("rollback_boundary_count", 0),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_signed_authorization_receipt_evidence_intake": (
            future_signed_authorization_receipt_evidence_intake
        ),
        "detached_verification_evidence_schema": detached_verification_evidence_schema,
        "signed_receipt_evidence_intake_contract": signed_receipt_evidence_intake_contract,
        "signed_receipt_evidence_intake_checks": checks,
        "source_signed_receipt_closeout_summary": summary,
        "source_signed_receipt_closeout_contract": closeout_contract,
        "source_detached_receipt_verification_boundary": detached_boundary,
        "safety": {
            "read_only_db_apply_authorization_signed_receipt_evidence_intake": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this intake schema for a future detached verification evidence validation lane.",
            "Keep signed receipt body, signature material, secret values, shell execution, SQL, and DB writes out of the AI payload.",
            "Only a later verifier lane may validate detached signature evidence; this intake still does not authorize DB apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_detached_verification_evidence_validation(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Validate the detached verification evidence schema without verifying signatures."""
    intake = build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_intake = intake.get("future_signed_authorization_receipt_evidence_intake") or {}
    schema = intake.get("detached_verification_evidence_schema") or {}
    intake_contract = intake.get("signed_receipt_evidence_intake_contract") or {}
    summary = intake.get("summary") or {}
    safety = intake.get("safety") or {}
    validation_id = _db_apply_authorization_detached_verification_evidence_validation_id(
        intake
    )
    required_external_evidence = list(schema.get("required_external_receipt_evidence") or [])
    external_acceptance_gates = list(schema.get("external_receipt_acceptance_gates") or [])
    detached_checks = list(schema.get("detached_receipt_verification_checks") or [])
    evidence_fields = list(schema.get("detached_verification_evidence_fields") or [])
    evidence_acceptance_gates = list(
        schema.get("detached_verification_acceptance_gates") or []
    )
    operator_secret_boundary = (
        schema.get("operator_held_secret_boundary_contract") or {}
    )
    verifier_receipt_fields = [
        "verifier_receipt_id",
        "source_signed_receipt_evidence_intake_id",
        "source_detached_verification_evidence_schema_id",
        "source_signed_receipt_closeout_id",
        "source_external_receipt_evidence_boundary_id",
        "external_receipt_id_reference",
        "payload_sha256",
        "receipt_sha256",
        "detached_signature_verification_status",
        "verifier_receipt_sha256",
        "verified_at_utc",
        "post_apply_verifier_endpoint",
    ]
    verifier_receipt_acceptance_gates = [
        "signed_receipt_evidence_intake_ready",
        "source_detached_verification_evidence_schema_id_matches",
        "source_external_receipt_evidence_boundary_id_matches",
        "payload_hash_matches_final_signable_request_package",
        "receipt_hash_is_present_and_nonempty",
        "signer_key_id_is_reference_only",
        "signature_algorithm_is_reference_only",
        "detached_signature_verification_status_passed",
        "no_secret_signature_or_signed_receipt_body_in_ai_payload",
        "post_apply_verifier_still_required",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("performs_detached_signature_verification") is False
        and schema.get("detached_signature_verification_performed") is False
        and schema.get("external_signed_authorization_receipt_included") is False
        and schema.get("signed_authorization_receipt_included") is False
        and schema.get("signature_material_included") is False
        and schema.get("secret_material_included") is False
        and schema.get("secret_material_required_in_preview") is False
        and schema.get("accepts_plaintext_secret") is False
        and schema.get("reads_secret_in_preview") is False
        and schema.get("executes_shell_in_preview") is False
        and schema.get("executes_sql_in_preview") is False
        and schema.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_detached_verification_evidence_validation_check(
            "signed_receipt_evidence_intake_ready",
            intake.get("result")
            == "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_READY"
            and future_intake.get(
                "ready_for_future_signed_authorization_receipt_evidence_intake"
            )
            is True
            and schema.get("ready_for_future_detached_verification_evidence_schema")
            is True,
            {
                "result": intake.get("result"),
                "ready_for_future_signed_authorization_receipt_evidence_intake": (
                    future_intake.get(
                        "ready_for_future_signed_authorization_receipt_evidence_intake"
                    )
                ),
                "ready_for_future_detached_verification_evidence_schema": schema.get(
                    "ready_for_future_detached_verification_evidence_schema"
                ),
            },
            "wait_for_signed_receipt_evidence_intake",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "detached_verification_evidence_schema_complete",
            schema.get("authorization_material_type")
            == "detached_verification_evidence_schema"
            and bool(schema.get("schema_id"))
            and bool(schema.get("source_signed_receipt_closeout_id"))
            and bool(schema.get("source_detached_receipt_verification_boundary_id"))
            and schema.get("ready_for_database_apply_now") is False
            and schema.get("issues_database_apply_authorization") is False
            and schema.get("signs_database_apply_authorization") is False,
            {
                "schema_id": schema.get("schema_id"),
                "authorization_material_type": schema.get("authorization_material_type"),
                "source_detached_receipt_verification_boundary_id": schema.get(
                    "source_detached_receipt_verification_boundary_id"
                ),
            },
            "wait_for_detached_verification_evidence_schema",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "source_chain_ids_present",
            bool(future_intake.get("intake_id"))
            and bool(future_intake.get("source_signed_receipt_closeout_id"))
            and bool(future_intake.get("source_detached_receipt_verification_boundary_id"))
            and bool(future_intake.get("source_external_receipt_evidence_boundary_id"))
            and bool(schema.get("source_final_signable_request_package_id")),
            {
                "intake_id": future_intake.get("intake_id"),
                "source_signed_receipt_closeout_id": future_intake.get(
                    "source_signed_receipt_closeout_id"
                ),
                "source_final_signable_request_package_id": schema.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "external_receipt_contract_carried_forward",
            len(required_external_evidence) == 10
            and len(external_acceptance_gates) == 8
            and int(summary.get("required_external_receipt_evidence_count") or 0) == 10
            and int(summary.get("external_receipt_acceptance_gate_count") or 0) == 8,
            {
                "required_external_receipt_evidence_count": len(required_external_evidence),
                "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
                "summary_required_external_receipt_evidence_count": summary.get(
                    "required_external_receipt_evidence_count", 0
                ),
                "summary_external_receipt_acceptance_gate_count": summary.get(
                    "external_receipt_acceptance_gate_count", 0
                ),
            },
            "wait_for_external_receipt_contract",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "detached_verification_evidence_requirements_carried_forward",
            len(detached_checks) == 10
            and len(evidence_fields) == 12
            and len(evidence_acceptance_gates) == 10
            and int(summary.get("detached_verification_evidence_field_count") or 0) == 12
            and int(summary.get("detached_verification_acceptance_gate_count") or 0) == 10,
            {
                "detached_receipt_verification_check_count": len(detached_checks),
                "detached_verification_evidence_field_count": len(evidence_fields),
                "detached_verification_acceptance_gate_count": len(
                    evidence_acceptance_gates
                ),
            },
            "wait_for_detached_verification_evidence_requirements",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "verifier_receipt_closeout_boundary_contract_complete",
            len(verifier_receipt_fields) == 12
            and len(verifier_receipt_acceptance_gates) == 10
            and "detached_signature_verification_status_passed"
            in verifier_receipt_acceptance_gates
            and "verifier_receipt_sha256" in verifier_receipt_fields,
            {
                "verifier_receipt_field_count": len(verifier_receipt_fields),
                "verifier_receipt_acceptance_gate_count": len(
                    verifier_receipt_acceptance_gates
                ),
                "requires_status_passed": (
                    "detached_signature_verification_status_passed"
                    in verifier_receipt_acceptance_gates
                ),
            },
            "wait_for_verifier_receipt_closeout_boundary_contract",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "signer_and_algorithm_references_only",
            schema.get("signer_key_id_reference_only") is True
            and schema.get("signature_algorithm_reference_only") is True
            and "signer_key_id_reference" in evidence_fields
            and "signature_algorithm_reference" in evidence_fields,
            {
                "signer_key_id_reference_only": schema.get(
                    "signer_key_id_reference_only"
                ),
                "signature_algorithm_reference_only": schema.get(
                    "signature_algorithm_reference_only"
                ),
            },
            "abort_on_plaintext_key_or_algorithm_material",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "secret_and_signed_material_boundary_enforced",
            schema.get("detached_signature_verification_performed") is False
            and schema.get("external_signed_authorization_receipt_included") is False
            and schema.get("signed_authorization_receipt_included") is False
            and schema.get("signature_material_included") is False
            and schema.get("secret_material_included") is False
            and schema.get("accepts_plaintext_secret") is False
            and operator_secret_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_secret_boundary.get("accepts_plaintext_secret") is False,
            {
                "detached_signature_verification_performed": schema.get(
                    "detached_signature_verification_performed"
                ),
                "external_signed_authorization_receipt_included": schema.get(
                    "external_signed_authorization_receipt_included"
                ),
                "signature_material_included": schema.get("signature_material_included"),
                "accepts_plaintext_secret": schema.get("accepts_plaintext_secret"),
                "secret_reference_mode": operator_secret_boundary.get(
                    "secret_reference_mode"
                ),
            },
            "abort_on_signed_material_or_secret_boundary_violation",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "same_run_production_truth_required",
            schema.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": schema.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "post_apply_verifier_and_hash_lock_required",
            schema.get("requires_post_apply_verifier") is True
            and bool(schema.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1
            and schema.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and schema.get("hash_matches") is True
            and bool(schema.get("expected_sha256"))
            and schema.get("expected_sha256") == schema.get("actual_sha256"),
            {
                "requires_post_apply_verifier": schema.get("requires_post_apply_verifier"),
                "post_apply_verifier_endpoint": schema.get("post_apply_verifier_endpoint"),
                "target_file": schema.get("target_file"),
                "hash_matches": schema.get("hash_matches"),
            },
            "require_post_apply_verifier_and_hash_lock",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "preview_has_no_side_effects_no_verification_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "performs_detached_signature_verification": safety.get(
                    "performs_detached_signature_verification"
                ),
            },
            "abort_on_preview_side_effect_verification_or_signing",
        ),
        _authorization_detached_verification_evidence_validation_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_intake.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": future_intake.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    validation_ready = not waiting_checks
    validation_status = (
        "DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_READY"
        if validation_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE"
    )
    future_detached_verification_evidence_validation = {
        "validation_id": validation_id,
        "source_signed_receipt_evidence_intake_id": future_intake.get("intake_id"),
        "source_detached_verification_evidence_schema_id": schema.get("schema_id"),
        "source_signed_receipt_closeout_id": schema.get(
            "source_signed_receipt_closeout_id"
        ),
        "source_detached_receipt_verification_boundary_id": schema.get(
            "source_detached_receipt_verification_boundary_id"
        ),
        "source_external_receipt_evidence_boundary_id": schema.get(
            "source_external_receipt_evidence_boundary_id"
        ),
        "source_final_signable_request_package_id": schema.get(
            "source_final_signable_request_package_id"
        ),
        "status": validation_status,
        "ready_for_future_detached_verification_evidence_validation": validation_ready,
        "can_enter_future_verifier_receipt_closeout": validation_ready,
        "verifier_receipt_closeout_boundary_ready": validation_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    verifier_receipt_closeout_boundary = {
        "boundary_id": validation_id,
        "authorization_material_type": "verifier_receipt_closeout_boundary",
        "source_signed_receipt_evidence_intake_id": future_intake.get("intake_id"),
        "source_detached_verification_evidence_schema_id": schema.get("schema_id"),
        "source_signed_receipt_closeout_id": schema.get(
            "source_signed_receipt_closeout_id"
        ),
        "source_detached_receipt_verification_boundary_id": schema.get(
            "source_detached_receipt_verification_boundary_id"
        ),
        "source_external_receipt_evidence_boundary_id": schema.get(
            "source_external_receipt_evidence_boundary_id"
        ),
        "source_final_signable_request_package_id": schema.get(
            "source_final_signable_request_package_id"
        ),
        "status": validation_status,
        "ready_for_future_verifier_receipt_closeout_boundary": validation_ready,
        "required_external_receipt_evidence": required_external_evidence,
        "required_external_receipt_evidence_count": len(required_external_evidence),
        "external_receipt_acceptance_gates": external_acceptance_gates,
        "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
        "detached_receipt_verification_checks": detached_checks,
        "detached_receipt_verification_check_count": len(detached_checks),
        "detached_verification_evidence_fields": evidence_fields,
        "detached_verification_evidence_field_count": len(evidence_fields),
        "detached_verification_acceptance_gates": evidence_acceptance_gates,
        "detached_verification_acceptance_gate_count": len(evidence_acceptance_gates),
        "verifier_receipt_fields": verifier_receipt_fields,
        "verifier_receipt_field_count": len(verifier_receipt_fields),
        "verifier_receipt_acceptance_gates": verifier_receipt_acceptance_gates,
        "verifier_receipt_acceptance_gate_count": len(verifier_receipt_acceptance_gates),
        "requires_detached_signature_verification": True,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "operator_held_secret_boundary_contract": operator_secret_boundary,
        "target_file": schema.get("target_file"),
        "expected_sha256": schema.get("expected_sha256"),
        "actual_sha256": schema.get("actual_sha256"),
        "hash_matches": schema.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": schema.get("post_apply_verifier_endpoint"),
    }
    detached_verification_evidence_validation_contract = {
        "mode": "detached_verification_evidence_validation_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-detached-verification-evidence-validation"
        ),
        "source_signed_receipt_evidence_intake_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-evidence-intake"
        ),
        "machine_verifiable": True,
        "permits_future_verifier_receipt_closeout": validation_ready,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_POLICY,
        "result": validation_status,
        "success": bool(intake.get("success")),
        "generated_at": intake.get("generated_at"),
        "source_policy": intake.get("policy"),
        "stats": intake.get("stats") or {},
        "summary": {
            "authorization_detached_verification_evidence_validation_ready_count": (
                1 if validation_ready else 0
            ),
            "detached_verification_evidence_validation_check_count": len(checks),
            "detached_verification_evidence_validation_pass_count": passed_count,
            "detached_verification_evidence_validation_waiting_count": len(waiting_checks),
            "authorization_signed_receipt_evidence_intake_ready_count": summary.get(
                "authorization_signed_receipt_evidence_intake_ready_count", 0
            ),
            "signed_receipt_evidence_intake_check_count": summary.get(
                "signed_receipt_evidence_intake_check_count", 0
            ),
            "authorization_signed_receipt_closeout_ready_count": summary.get(
                "authorization_signed_receipt_closeout_ready_count", 0
            ),
            "signed_receipt_closeout_check_count": summary.get(
                "signed_receipt_closeout_check_count", 0
            ),
            "detached_receipt_verification_boundary_count": summary.get(
                "detached_receipt_verification_boundary_count", 0
            ),
            "detached_verification_evidence_schema_count": summary.get(
                "detached_verification_evidence_schema_count", 0
            ),
            "verifier_receipt_closeout_boundary_count": 1,
            "required_external_receipt_evidence_count": summary.get(
                "required_external_receipt_evidence_count", 0
            ),
            "external_receipt_acceptance_gate_count": summary.get(
                "external_receipt_acceptance_gate_count", 0
            ),
            "detached_receipt_verification_check_count": summary.get(
                "detached_receipt_verification_check_count", 0
            ),
            "detached_verification_evidence_field_count": summary.get(
                "detached_verification_evidence_field_count", 0
            ),
            "detached_verification_acceptance_gate_count": summary.get(
                "detached_verification_acceptance_gate_count", 0
            ),
            "verifier_receipt_field_count": len(verifier_receipt_fields),
            "verifier_receipt_acceptance_gate_count": len(
                verifier_receipt_acceptance_gates
            ),
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_detached_verification_evidence_validation": (
            future_detached_verification_evidence_validation
        ),
        "verifier_receipt_closeout_boundary": verifier_receipt_closeout_boundary,
        "detached_verification_evidence_validation_contract": (
            detached_verification_evidence_validation_contract
        ),
        "detached_verification_evidence_validation_checks": checks,
        "source_signed_receipt_evidence_intake_summary": summary,
        "source_signed_receipt_evidence_intake_contract": intake_contract,
        "source_detached_verification_evidence_schema": schema,
        "safety": {
            "read_only_db_apply_authorization_detached_verification_evidence_validation": (
                True
            ),
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this validation boundary for a future verifier receipt closeout lane.",
            "Keep signed receipt body, signature material, secret values, shell execution, SQL, and DB writes out of the AI payload.",
            "Only a separate verifier receipt closeout may carry validation receipts; this validation lane still does not authorize DB apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_verifier_receipt_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out verifier receipt evidence handoff without persisting receipts."""
    validation = (
        build_pchome_auto_policy_db_apply_authorization_detached_verification_evidence_validation(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_validation = validation.get("future_detached_verification_evidence_validation") or {}
    boundary = validation.get("verifier_receipt_closeout_boundary") or {}
    validation_contract = (
        validation.get("detached_verification_evidence_validation_contract") or {}
    )
    summary = validation.get("summary") or {}
    safety = validation.get("safety") or {}
    closeout_id = _db_apply_authorization_verifier_receipt_closeout_id(validation)
    required_external_evidence = list(boundary.get("required_external_receipt_evidence") or [])
    external_acceptance_gates = list(boundary.get("external_receipt_acceptance_gates") or [])
    verifier_receipt_fields = list(boundary.get("verifier_receipt_fields") or [])
    verifier_receipt_acceptance_gates = list(
        boundary.get("verifier_receipt_acceptance_gates") or []
    )
    evidence_fields = list(boundary.get("detached_verification_evidence_fields") or [])
    evidence_acceptance_gates = list(
        boundary.get("detached_verification_acceptance_gates") or []
    )
    operator_secret_boundary = (
        boundary.get("operator_held_secret_boundary_contract") or {}
    )
    verifier_receipt_evidence_handoff_fields = [
        "handoff_id",
        "source_verifier_receipt_closeout_boundary_id",
        "source_detached_verification_evidence_validation_id",
        "source_signed_receipt_evidence_intake_id",
        "source_final_signable_request_package_id",
        "verifier_receipt_id_reference",
        "external_receipt_id_reference",
        "payload_sha256",
        "receipt_sha256",
        "verifier_receipt_sha256",
        "detached_signature_verification_status",
        "post_apply_verifier_endpoint",
    ]
    verifier_receipt_handoff_acceptance_gates = [
        "detached_verification_evidence_validation_ready",
        "verifier_receipt_closeout_boundary_ready",
        "source_chain_ids_match",
        "payload_hash_matches_final_signable_request_package",
        "receipt_hash_is_present_and_nonempty",
        "verifier_receipt_hash_is_present_and_nonempty",
        "detached_signature_verification_status_passed",
        "no_secret_signature_or_signed_receipt_body_in_ai_payload",
        "verifier_receipt_not_persisted_by_preview",
        "post_apply_verifier_still_required",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("performs_detached_signature_verification") is False
        and safety.get("persists_verifier_receipt") is False
        and boundary.get("detached_signature_verification_performed") is False
        and boundary.get("verifier_receipt_persisted") is False
        and boundary.get("external_signed_authorization_receipt_included") is False
        and boundary.get("signed_authorization_receipt_included") is False
        and boundary.get("signature_material_included") is False
        and boundary.get("secret_material_included") is False
        and boundary.get("secret_material_required_in_preview") is False
        and boundary.get("accepts_plaintext_secret") is False
        and boundary.get("reads_secret_in_preview") is False
        and boundary.get("executes_shell_in_preview") is False
        and boundary.get("executes_sql_in_preview") is False
        and boundary.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_verifier_receipt_closeout_check(
            "detached_verification_evidence_validation_ready",
            validation.get("result")
            == "DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_READY"
            and future_validation.get(
                "ready_for_future_detached_verification_evidence_validation"
            )
            is True
            and boundary.get("ready_for_future_verifier_receipt_closeout_boundary")
            is True,
            {
                "result": validation.get("result"),
                "ready_for_future_detached_verification_evidence_validation": (
                    future_validation.get(
                        "ready_for_future_detached_verification_evidence_validation"
                    )
                ),
                "ready_for_future_verifier_receipt_closeout_boundary": boundary.get(
                    "ready_for_future_verifier_receipt_closeout_boundary"
                ),
            },
            "wait_for_detached_verification_evidence_validation",
        ),
        _authorization_verifier_receipt_closeout_check(
            "verifier_receipt_closeout_boundary_complete",
            boundary.get("authorization_material_type")
            == "verifier_receipt_closeout_boundary"
            and bool(boundary.get("boundary_id"))
            and bool(boundary.get("source_detached_verification_evidence_schema_id"))
            and bool(boundary.get("source_signed_receipt_evidence_intake_id"))
            and boundary.get("ready_for_database_apply_now") is False
            and boundary.get("issues_database_apply_authorization") is False
            and boundary.get("signs_database_apply_authorization") is False,
            {
                "boundary_id": boundary.get("boundary_id"),
                "authorization_material_type": boundary.get("authorization_material_type"),
                "source_detached_verification_evidence_schema_id": boundary.get(
                    "source_detached_verification_evidence_schema_id"
                ),
            },
            "wait_for_verifier_receipt_closeout_boundary",
        ),
        _authorization_verifier_receipt_closeout_check(
            "source_chain_ids_present",
            bool(future_validation.get("validation_id"))
            and bool(future_validation.get("source_signed_receipt_evidence_intake_id"))
            and bool(future_validation.get("source_detached_verification_evidence_schema_id"))
            and bool(future_validation.get("source_signed_receipt_closeout_id"))
            and bool(boundary.get("source_final_signable_request_package_id")),
            {
                "validation_id": future_validation.get("validation_id"),
                "source_signed_receipt_evidence_intake_id": future_validation.get(
                    "source_signed_receipt_evidence_intake_id"
                ),
                "source_final_signable_request_package_id": boundary.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_verifier_receipt_closeout_check(
            "verifier_receipt_contract_carried_forward",
            len(verifier_receipt_fields) == 12
            and len(verifier_receipt_acceptance_gates) == 10
            and int(summary.get("verifier_receipt_field_count") or 0) == 12
            and int(summary.get("verifier_receipt_acceptance_gate_count") or 0) == 10,
            {
                "verifier_receipt_field_count": len(verifier_receipt_fields),
                "verifier_receipt_acceptance_gate_count": len(
                    verifier_receipt_acceptance_gates
                ),
                "summary_verifier_receipt_field_count": summary.get(
                    "verifier_receipt_field_count", 0
                ),
                "summary_verifier_receipt_acceptance_gate_count": summary.get(
                    "verifier_receipt_acceptance_gate_count", 0
                ),
            },
            "wait_for_verifier_receipt_contract",
        ),
        _authorization_verifier_receipt_closeout_check(
            "detached_evidence_and_external_receipt_contracts_carried_forward",
            len(required_external_evidence) == 10
            and len(external_acceptance_gates) == 8
            and len(evidence_fields) == 12
            and len(evidence_acceptance_gates) == 10,
            {
                "required_external_receipt_evidence_count": len(required_external_evidence),
                "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
                "detached_verification_evidence_field_count": len(evidence_fields),
                "detached_verification_acceptance_gate_count": len(
                    evidence_acceptance_gates
                ),
            },
            "wait_for_detached_evidence_or_external_receipt_contract",
        ),
        _authorization_verifier_receipt_closeout_check(
            "verifier_receipt_evidence_handoff_contract_complete",
            len(verifier_receipt_evidence_handoff_fields) == 12
            and len(verifier_receipt_handoff_acceptance_gates) == 10
            and "verifier_receipt_sha256" in verifier_receipt_evidence_handoff_fields
            and "verifier_receipt_not_persisted_by_preview"
            in verifier_receipt_handoff_acceptance_gates,
            {
                "verifier_receipt_evidence_handoff_field_count": len(
                    verifier_receipt_evidence_handoff_fields
                ),
                "verifier_receipt_handoff_acceptance_gate_count": len(
                    verifier_receipt_handoff_acceptance_gates
                ),
            },
            "wait_for_verifier_receipt_evidence_handoff_contract",
        ),
        _authorization_verifier_receipt_closeout_check(
            "secret_signed_material_and_receipt_persistence_boundary_enforced",
            boundary.get("detached_signature_verification_performed") is False
            and boundary.get("verifier_receipt_persisted") is False
            and boundary.get("external_signed_authorization_receipt_included") is False
            and boundary.get("signed_authorization_receipt_included") is False
            and boundary.get("signature_material_included") is False
            and boundary.get("secret_material_included") is False
            and boundary.get("accepts_plaintext_secret") is False
            and operator_secret_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_secret_boundary.get("accepts_plaintext_secret") is False,
            {
                "detached_signature_verification_performed": boundary.get(
                    "detached_signature_verification_performed"
                ),
                "verifier_receipt_persisted": boundary.get(
                    "verifier_receipt_persisted"
                ),
                "external_signed_authorization_receipt_included": boundary.get(
                    "external_signed_authorization_receipt_included"
                ),
                "signature_material_included": boundary.get("signature_material_included"),
                "accepts_plaintext_secret": boundary.get("accepts_plaintext_secret"),
            },
            "abort_on_signed_material_secret_or_receipt_persistence",
        ),
        _authorization_verifier_receipt_closeout_check(
            "same_run_production_truth_required",
            boundary.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": boundary.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_verifier_receipt_closeout_check(
            "post_apply_verifier_and_hash_lock_required",
            boundary.get("requires_post_apply_verifier") is True
            and bool(boundary.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1
            and boundary.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and boundary.get("hash_matches") is True
            and bool(boundary.get("expected_sha256"))
            and boundary.get("expected_sha256") == boundary.get("actual_sha256"),
            {
                "requires_post_apply_verifier": boundary.get("requires_post_apply_verifier"),
                "post_apply_verifier_endpoint": boundary.get(
                    "post_apply_verifier_endpoint"
                ),
                "target_file": boundary.get("target_file"),
                "hash_matches": boundary.get("hash_matches"),
            },
            "require_post_apply_verifier_and_hash_lock",
        ),
        _authorization_verifier_receipt_closeout_check(
            "closeout_contract_blocks_database_apply",
            validation_contract.get("permits_future_verifier_receipt_closeout") is True
            and validation_contract.get("issues_database_apply_authorization") is False
            and validation_contract.get("ready_for_database_apply_now") is False
            and validation_contract.get("signs_database_apply_authorization") is False
            and validation_contract.get("persists_verifier_receipt") is False
            and validation_contract.get("performs_detached_signature_verification") is False,
            {
                "permits_future_verifier_receipt_closeout": validation_contract.get(
                    "permits_future_verifier_receipt_closeout"
                ),
                "ready_for_database_apply_now": validation_contract.get(
                    "ready_for_database_apply_now"
                ),
                "persists_verifier_receipt": validation_contract.get(
                    "persists_verifier_receipt"
                ),
            },
            "abort_if_validation_contract_authorizes_database_apply",
        ),
        _authorization_verifier_receipt_closeout_check(
            "preview_has_no_side_effects_no_verification_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "performs_detached_signature_verification": safety.get(
                    "performs_detached_signature_verification"
                ),
                "persists_verifier_receipt": safety.get("persists_verifier_receipt"),
            },
            "abort_on_preview_side_effect_verification_signing_or_persistence",
        ),
        _authorization_verifier_receipt_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_validation.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": future_validation.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION"
    )
    future_verifier_receipt_closeout = {
        "closeout_id": closeout_id,
        "source_detached_verification_evidence_validation_id": future_validation.get(
            "validation_id"
        ),
        "source_verifier_receipt_closeout_boundary_id": boundary.get("boundary_id"),
        "source_signed_receipt_evidence_intake_id": boundary.get(
            "source_signed_receipt_evidence_intake_id"
        ),
        "source_detached_verification_evidence_schema_id": boundary.get(
            "source_detached_verification_evidence_schema_id"
        ),
        "source_final_signable_request_package_id": boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": closeout_status,
        "ready_for_future_verifier_receipt_closeout": closeout_ready,
        "can_enter_future_database_apply_authorization_verifier_handoff": closeout_ready,
        "verifier_receipt_evidence_handoff_ready": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    verifier_receipt_evidence_handoff = {
        "handoff_id": closeout_id,
        "authorization_material_type": "verifier_receipt_evidence_handoff",
        "source_detached_verification_evidence_validation_id": future_validation.get(
            "validation_id"
        ),
        "source_verifier_receipt_closeout_boundary_id": boundary.get("boundary_id"),
        "source_signed_receipt_evidence_intake_id": boundary.get(
            "source_signed_receipt_evidence_intake_id"
        ),
        "source_detached_verification_evidence_schema_id": boundary.get(
            "source_detached_verification_evidence_schema_id"
        ),
        "source_signed_receipt_closeout_id": boundary.get(
            "source_signed_receipt_closeout_id"
        ),
        "source_external_receipt_evidence_boundary_id": boundary.get(
            "source_external_receipt_evidence_boundary_id"
        ),
        "source_final_signable_request_package_id": boundary.get(
            "source_final_signable_request_package_id"
        ),
        "status": closeout_status,
        "ready_for_future_verifier_receipt_evidence_handoff": closeout_ready,
        "required_external_receipt_evidence": required_external_evidence,
        "required_external_receipt_evidence_count": len(required_external_evidence),
        "external_receipt_acceptance_gates": external_acceptance_gates,
        "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
        "verifier_receipt_fields": verifier_receipt_fields,
        "verifier_receipt_field_count": len(verifier_receipt_fields),
        "verifier_receipt_acceptance_gates": verifier_receipt_acceptance_gates,
        "verifier_receipt_acceptance_gate_count": len(verifier_receipt_acceptance_gates),
        "verifier_receipt_evidence_handoff_fields": (
            verifier_receipt_evidence_handoff_fields
        ),
        "verifier_receipt_evidence_handoff_field_count": len(
            verifier_receipt_evidence_handoff_fields
        ),
        "verifier_receipt_handoff_acceptance_gates": (
            verifier_receipt_handoff_acceptance_gates
        ),
        "verifier_receipt_handoff_acceptance_gate_count": len(
            verifier_receipt_handoff_acceptance_gates
        ),
        "requires_detached_signature_verification": True,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "operator_held_secret_boundary_contract": operator_secret_boundary,
        "target_file": boundary.get("target_file"),
        "expected_sha256": boundary.get("expected_sha256"),
        "actual_sha256": boundary.get("actual_sha256"),
        "hash_matches": boundary.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": boundary.get("post_apply_verifier_endpoint"),
    }
    verifier_receipt_closeout_contract = {
        "mode": "verifier_receipt_closeout_handoff_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-verifier-receipt-closeout"
        ),
        "source_detached_verification_evidence_validation_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-detached-verification-evidence-validation"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_authorization_verifier_handoff": closeout_ready,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(validation.get("success")),
        "generated_at": validation.get("generated_at"),
        "source_policy": validation.get("policy"),
        "stats": validation.get("stats") or {},
        "summary": {
            "authorization_verifier_receipt_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "verifier_receipt_closeout_check_count": len(checks),
            "verifier_receipt_closeout_pass_count": passed_count,
            "verifier_receipt_closeout_waiting_count": len(waiting_checks),
            "authorization_detached_verification_evidence_validation_ready_count": (
                summary.get(
                    "authorization_detached_verification_evidence_validation_ready_count",
                    0,
                )
            ),
            "detached_verification_evidence_validation_check_count": summary.get(
                "detached_verification_evidence_validation_check_count", 0
            ),
            "authorization_signed_receipt_evidence_intake_ready_count": summary.get(
                "authorization_signed_receipt_evidence_intake_ready_count", 0
            ),
            "signed_receipt_evidence_intake_check_count": summary.get(
                "signed_receipt_evidence_intake_check_count", 0
            ),
            "verifier_receipt_closeout_boundary_count": summary.get(
                "verifier_receipt_closeout_boundary_count", 0
            ),
            "verifier_receipt_evidence_handoff_count": 1,
            "required_external_receipt_evidence_count": summary.get(
                "required_external_receipt_evidence_count", 0
            ),
            "external_receipt_acceptance_gate_count": summary.get(
                "external_receipt_acceptance_gate_count", 0
            ),
            "verifier_receipt_field_count": summary.get(
                "verifier_receipt_field_count", 0
            ),
            "verifier_receipt_acceptance_gate_count": summary.get(
                "verifier_receipt_acceptance_gate_count", 0
            ),
            "verifier_receipt_evidence_handoff_field_count": len(
                verifier_receipt_evidence_handoff_fields
            ),
            "verifier_receipt_handoff_acceptance_gate_count": len(
                verifier_receipt_handoff_acceptance_gates
            ),
            "detached_verification_evidence_field_count": summary.get(
                "detached_verification_evidence_field_count", 0
            ),
            "detached_verification_acceptance_gate_count": summary.get(
                "detached_verification_acceptance_gate_count", 0
            ),
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_verifier_receipt_closeout": future_verifier_receipt_closeout,
        "verifier_receipt_evidence_handoff": verifier_receipt_evidence_handoff,
        "verifier_receipt_closeout_contract": verifier_receipt_closeout_contract,
        "verifier_receipt_closeout_checks": checks,
        "source_detached_verification_evidence_validation_summary": summary,
        "source_detached_verification_evidence_validation_contract": validation_contract,
        "source_verifier_receipt_closeout_boundary": boundary,
        "safety": {
            "read_only_db_apply_authorization_verifier_receipt_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this verifier receipt closeout as the evidence handoff for a future database apply authorization verifier lane.",
            "Keep signed receipt body, signature material, secret values, shell execution, SQL, and DB writes out of this handoff.",
            "A later verifier handoff may accept external verifier receipts; this closeout still does not authorize DB apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_evidence_execution_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Preflight future authorization evidence execution without executing it."""
    closeout = build_pchome_auto_policy_db_apply_authorization_verifier_receipt_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_closeout = closeout.get("future_verifier_receipt_closeout") or {}
    handoff = closeout.get("verifier_receipt_evidence_handoff") or {}
    closeout_contract = closeout.get("verifier_receipt_closeout_contract") or {}
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    preflight_id = _db_apply_authorization_evidence_execution_preflight_id(closeout)
    verifier_receipt_fields = list(handoff.get("verifier_receipt_fields") or [])
    verifier_receipt_acceptance_gates = list(
        handoff.get("verifier_receipt_acceptance_gates") or []
    )
    handoff_fields = list(
        handoff.get("verifier_receipt_evidence_handoff_fields") or []
    )
    handoff_acceptance_gates = list(
        handoff.get("verifier_receipt_handoff_acceptance_gates") or []
    )
    required_external_evidence = list(handoff.get("required_external_receipt_evidence") or [])
    external_acceptance_gates = list(handoff.get("external_receipt_acceptance_gates") or [])
    operator_secret_boundary = (
        handoff.get("operator_held_secret_boundary_contract") or {}
    )
    authorization_evidence_execution_fields = [
        "execution_preflight_id",
        "source_verifier_receipt_closeout_id",
        "source_verifier_receipt_evidence_handoff_id",
        "source_detached_verification_evidence_validation_id",
        "source_final_signable_request_package_id",
        "verifier_receipt_id_reference",
        "external_receipt_id_reference",
        "payload_sha256",
        "receipt_sha256",
        "verifier_receipt_sha256",
        "detached_signature_verification_status",
        "post_apply_verifier_endpoint",
    ]
    authorization_evidence_execution_acceptance_gates = [
        "verifier_receipt_closeout_ready",
        "verifier_receipt_evidence_handoff_ready",
        "source_chain_ids_match",
        "production_truth_matches_preflight_run",
        "payload_hash_matches_final_signable_request_package",
        "receipt_hash_is_present_and_nonempty",
        "verifier_receipt_hash_is_present_and_nonempty",
        "detached_signature_verification_status_passed",
        "post_apply_verifier_still_required",
        "no_secret_signature_or_database_write_in_preflight",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("performs_detached_signature_verification") is False
        and safety.get("persists_verifier_receipt") is False
        and handoff.get("detached_signature_verification_performed") is False
        and handoff.get("verifier_receipt_persisted") is False
        and handoff.get("external_signed_authorization_receipt_included") is False
        and handoff.get("signed_authorization_receipt_included") is False
        and handoff.get("signature_material_included") is False
        and handoff.get("secret_material_included") is False
        and handoff.get("secret_material_required_in_preview") is False
        and handoff.get("accepts_plaintext_secret") is False
        and handoff.get("reads_secret_in_preview") is False
        and handoff.get("executes_shell_in_preview") is False
        and handoff.get("executes_sql_in_preview") is False
        and handoff.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_evidence_execution_preflight_check(
            "verifier_receipt_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_READY"
            and future_closeout.get("ready_for_future_verifier_receipt_closeout") is True
            and handoff.get("ready_for_future_verifier_receipt_evidence_handoff") is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_verifier_receipt_closeout": future_closeout.get(
                    "ready_for_future_verifier_receipt_closeout"
                ),
                "ready_for_future_verifier_receipt_evidence_handoff": handoff.get(
                    "ready_for_future_verifier_receipt_evidence_handoff"
                ),
            },
            "wait_for_verifier_receipt_closeout",
        ),
        _authorization_evidence_execution_preflight_check(
            "verifier_receipt_evidence_handoff_complete",
            handoff.get("authorization_material_type") == "verifier_receipt_evidence_handoff"
            and bool(handoff.get("handoff_id"))
            and bool(handoff.get("source_detached_verification_evidence_validation_id"))
            and bool(handoff.get("source_final_signable_request_package_id"))
            and handoff.get("ready_for_database_apply_now") is False
            and handoff.get("issues_database_apply_authorization") is False
            and handoff.get("signs_database_apply_authorization") is False,
            {
                "handoff_id": handoff.get("handoff_id"),
                "authorization_material_type": handoff.get("authorization_material_type"),
                "source_final_signable_request_package_id": handoff.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_verifier_receipt_evidence_handoff",
        ),
        _authorization_evidence_execution_preflight_check(
            "source_chain_ids_present",
            bool(future_closeout.get("closeout_id"))
            and bool(future_closeout.get("source_detached_verification_evidence_validation_id"))
            and bool(future_closeout.get("source_verifier_receipt_closeout_boundary_id"))
            and bool(future_closeout.get("source_signed_receipt_evidence_intake_id"))
            and bool(handoff.get("source_final_signable_request_package_id")),
            {
                "closeout_id": future_closeout.get("closeout_id"),
                "source_detached_verification_evidence_validation_id": future_closeout.get(
                    "source_detached_verification_evidence_validation_id"
                ),
                "source_final_signable_request_package_id": handoff.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_evidence_execution_preflight_check(
            "verifier_receipt_handoff_contract_carried_forward",
            len(verifier_receipt_fields) == 12
            and len(verifier_receipt_acceptance_gates) == 10
            and len(handoff_fields) == 12
            and len(handoff_acceptance_gates) == 10
            and int(summary.get("verifier_receipt_field_count") or 0) == 12
            and int(summary.get("verifier_receipt_handoff_acceptance_gate_count") or 0)
            == 10,
            {
                "verifier_receipt_field_count": len(verifier_receipt_fields),
                "verifier_receipt_acceptance_gate_count": len(
                    verifier_receipt_acceptance_gates
                ),
                "verifier_receipt_evidence_handoff_field_count": len(handoff_fields),
                "verifier_receipt_handoff_acceptance_gate_count": len(
                    handoff_acceptance_gates
                ),
            },
            "wait_for_verifier_receipt_handoff_contract",
        ),
        _authorization_evidence_execution_preflight_check(
            "authorization_evidence_execution_preflight_contract_complete",
            len(authorization_evidence_execution_fields) == 12
            and len(authorization_evidence_execution_acceptance_gates) == 10
            and "verifier_receipt_sha256" in authorization_evidence_execution_fields
            and "no_secret_signature_or_database_write_in_preflight"
            in authorization_evidence_execution_acceptance_gates,
            {
                "authorization_evidence_execution_field_count": len(
                    authorization_evidence_execution_fields
                ),
                "authorization_evidence_execution_acceptance_gate_count": len(
                    authorization_evidence_execution_acceptance_gates
                ),
            },
            "wait_for_authorization_evidence_execution_preflight_contract",
        ),
        _authorization_evidence_execution_preflight_check(
            "external_receipt_contract_carried_forward",
            len(required_external_evidence) == 10
            and len(external_acceptance_gates) == 8
            and int(summary.get("required_external_receipt_evidence_count") or 0) == 10
            and int(summary.get("external_receipt_acceptance_gate_count") or 0) == 8,
            {
                "required_external_receipt_evidence_count": len(required_external_evidence),
                "external_receipt_acceptance_gate_count": len(external_acceptance_gates),
                "summary_required_external_receipt_evidence_count": summary.get(
                    "required_external_receipt_evidence_count", 0
                ),
                "summary_external_receipt_acceptance_gate_count": summary.get(
                    "external_receipt_acceptance_gate_count", 0
                ),
            },
            "wait_for_external_receipt_contract",
        ),
        _authorization_evidence_execution_preflight_check(
            "secret_signed_material_and_execution_boundary_enforced",
            handoff.get("detached_signature_verification_performed") is False
            and handoff.get("verifier_receipt_persisted") is False
            and handoff.get("external_signed_authorization_receipt_included") is False
            and handoff.get("signed_authorization_receipt_included") is False
            and handoff.get("signature_material_included") is False
            and handoff.get("secret_material_included") is False
            and handoff.get("accepts_plaintext_secret") is False
            and operator_secret_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and operator_secret_boundary.get("accepts_plaintext_secret") is False,
            {
                "detached_signature_verification_performed": handoff.get(
                    "detached_signature_verification_performed"
                ),
                "verifier_receipt_persisted": handoff.get("verifier_receipt_persisted"),
                "signature_material_included": handoff.get("signature_material_included"),
                "secret_material_included": handoff.get("secret_material_included"),
                "accepts_plaintext_secret": handoff.get("accepts_plaintext_secret"),
            },
            "abort_on_secret_signed_material_or_execution_boundary_violation",
        ),
        _authorization_evidence_execution_preflight_check(
            "same_run_production_truth_required",
            handoff.get("requires_fresh_production_truth_in_same_run") is True
            and int(summary.get("same_run_truth_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": handoff.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            },
            "require_same_run_production_truth",
        ),
        _authorization_evidence_execution_preflight_check(
            "post_apply_verifier_and_hash_lock_required",
            handoff.get("requires_post_apply_verifier") is True
            and bool(handoff.get("post_apply_verifier_endpoint"))
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1
            and handoff.get("target_file")
            == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
            and handoff.get("hash_matches") is True
            and bool(handoff.get("expected_sha256"))
            and handoff.get("expected_sha256") == handoff.get("actual_sha256"),
            {
                "requires_post_apply_verifier": handoff.get("requires_post_apply_verifier"),
                "post_apply_verifier_endpoint": handoff.get("post_apply_verifier_endpoint"),
                "target_file": handoff.get("target_file"),
                "hash_matches": handoff.get("hash_matches"),
            },
            "require_post_apply_verifier_and_hash_lock",
        ),
        _authorization_evidence_execution_preflight_check(
            "closeout_contract_blocks_database_apply",
            closeout_contract.get(
                "permits_future_database_apply_authorization_verifier_handoff"
            )
            is True
            and closeout_contract.get("issues_database_apply_authorization") is False
            and closeout_contract.get("ready_for_database_apply_now") is False
            and closeout_contract.get("signs_database_apply_authorization") is False
            and closeout_contract.get("persists_verifier_receipt") is False
            and closeout_contract.get("performs_detached_signature_verification") is False,
            {
                "permits_future_database_apply_authorization_verifier_handoff": (
                    closeout_contract.get(
                        "permits_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "ready_for_database_apply_now": closeout_contract.get(
                    "ready_for_database_apply_now"
                ),
                "persists_verifier_receipt": closeout_contract.get(
                    "persists_verifier_receipt"
                ),
            },
            "abort_if_closeout_contract_authorizes_database_apply",
        ),
        _authorization_evidence_execution_preflight_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "performs_detached_signature_verification": safety.get(
                    "performs_detached_signature_verification"
                ),
                "persists_verifier_receipt": safety.get("persists_verifier_receipt"),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _authorization_evidence_execution_preflight_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_closeout.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
                "manual_review_mode": future_closeout.get("manual_review_mode"),
            },
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    preflight_ready = not waiting_checks
    preflight_status = (
        "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_READY"
        if preflight_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT"
    )
    future_database_apply_authorization_verifier_handoff = {
        "preflight_id": preflight_id,
        "source_verifier_receipt_closeout_id": future_closeout.get("closeout_id"),
        "source_verifier_receipt_evidence_handoff_id": handoff.get("handoff_id"),
        "source_detached_verification_evidence_validation_id": handoff.get(
            "source_detached_verification_evidence_validation_id"
        ),
        "source_final_signable_request_package_id": handoff.get(
            "source_final_signable_request_package_id"
        ),
        "status": preflight_status,
        "ready_for_future_database_apply_authorization_verifier_handoff": (
            preflight_ready
        ),
        "can_enter_future_authorization_evidence_execution_closeout": preflight_ready,
        "authorization_evidence_execution_preflight_ready": preflight_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    authorization_evidence_execution_preflight = {
        "preflight_id": preflight_id,
        "authorization_material_type": "authorization_evidence_execution_preflight",
        "source_verifier_receipt_closeout_id": future_closeout.get("closeout_id"),
        "source_verifier_receipt_evidence_handoff_id": handoff.get("handoff_id"),
        "source_detached_verification_evidence_validation_id": handoff.get(
            "source_detached_verification_evidence_validation_id"
        ),
        "source_signed_receipt_evidence_intake_id": handoff.get(
            "source_signed_receipt_evidence_intake_id"
        ),
        "source_final_signable_request_package_id": handoff.get(
            "source_final_signable_request_package_id"
        ),
        "status": preflight_status,
        "ready_for_future_authorization_evidence_execution_preflight": (
            preflight_ready
        ),
        "authorization_evidence_execution_fields": authorization_evidence_execution_fields,
        "authorization_evidence_execution_field_count": len(
            authorization_evidence_execution_fields
        ),
        "authorization_evidence_execution_acceptance_gates": (
            authorization_evidence_execution_acceptance_gates
        ),
        "authorization_evidence_execution_acceptance_gate_count": len(
            authorization_evidence_execution_acceptance_gates
        ),
        "verifier_receipt_fields": verifier_receipt_fields,
        "verifier_receipt_field_count": len(verifier_receipt_fields),
        "verifier_receipt_acceptance_gates": verifier_receipt_acceptance_gates,
        "verifier_receipt_acceptance_gate_count": len(verifier_receipt_acceptance_gates),
        "verifier_receipt_evidence_handoff_fields": handoff_fields,
        "verifier_receipt_evidence_handoff_field_count": len(handoff_fields),
        "verifier_receipt_handoff_acceptance_gates": handoff_acceptance_gates,
        "verifier_receipt_handoff_acceptance_gate_count": len(handoff_acceptance_gates),
        "requires_detached_signature_verification": True,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "executes_authorization_evidence": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "operator_held_secret_boundary_contract": operator_secret_boundary,
        "target_file": handoff.get("target_file"),
        "expected_sha256": handoff.get("expected_sha256"),
        "actual_sha256": handoff.get("actual_sha256"),
        "hash_matches": handoff.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": handoff.get("post_apply_verifier_endpoint"),
    }
    authorization_evidence_execution_preflight_contract = {
        "mode": "authorization_evidence_execution_preflight_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-evidence-execution-preflight"
        ),
        "source_verifier_receipt_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-verifier-receipt-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_authorization_evidence_execution_closeout": preflight_ready,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_POLICY,
        "result": preflight_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_evidence_execution_preflight_ready_count": (
                1 if preflight_ready else 0
            ),
            "authorization_evidence_execution_preflight_check_count": len(checks),
            "authorization_evidence_execution_preflight_pass_count": passed_count,
            "authorization_evidence_execution_preflight_waiting_count": len(
                waiting_checks
            ),
            "authorization_verifier_receipt_closeout_ready_count": summary.get(
                "authorization_verifier_receipt_closeout_ready_count", 0
            ),
            "verifier_receipt_closeout_check_count": summary.get(
                "verifier_receipt_closeout_check_count", 0
            ),
            "authorization_detached_verification_evidence_validation_ready_count": (
                summary.get(
                    "authorization_detached_verification_evidence_validation_ready_count",
                    0,
                )
            ),
            "detached_verification_evidence_validation_check_count": summary.get(
                "detached_verification_evidence_validation_check_count", 0
            ),
            "verifier_receipt_evidence_handoff_count": summary.get(
                "verifier_receipt_evidence_handoff_count", 0
            ),
            "authorization_evidence_execution_preflight_count": 1,
            "authorization_evidence_execution_field_count": len(
                authorization_evidence_execution_fields
            ),
            "authorization_evidence_execution_acceptance_gate_count": len(
                authorization_evidence_execution_acceptance_gates
            ),
            "verifier_receipt_field_count": summary.get(
                "verifier_receipt_field_count", 0
            ),
            "verifier_receipt_acceptance_gate_count": summary.get(
                "verifier_receipt_acceptance_gate_count", 0
            ),
            "verifier_receipt_evidence_handoff_field_count": summary.get(
                "verifier_receipt_evidence_handoff_field_count", 0
            ),
            "verifier_receipt_handoff_acceptance_gate_count": summary.get(
                "verifier_receipt_handoff_acceptance_gate_count", 0
            ),
            "required_external_receipt_evidence_count": summary.get(
                "required_external_receipt_evidence_count", 0
            ),
            "external_receipt_acceptance_gate_count": summary.get(
                "external_receipt_acceptance_gate_count", 0
            ),
            "operator_held_secret_boundary_count": summary.get(
                "operator_held_secret_boundary_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_database_apply_authorization_verifier_handoff": (
            future_database_apply_authorization_verifier_handoff
        ),
        "authorization_evidence_execution_preflight": (
            authorization_evidence_execution_preflight
        ),
        "authorization_evidence_execution_preflight_contract": (
            authorization_evidence_execution_preflight_contract
        ),
        "authorization_evidence_execution_preflight_checks": checks,
        "source_verifier_receipt_closeout_summary": summary,
        "source_verifier_receipt_closeout_contract": closeout_contract,
        "source_verifier_receipt_evidence_handoff": handoff,
        "safety": {
            "read_only_db_apply_authorization_evidence_execution_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this preflight for a future authorization evidence execution closeout lane.",
            "Keep signed receipt body, signature material, secret values, shell execution, SQL, and DB writes out of this preflight.",
            "A later execution closeout may validate external evidence receipt readiness; this preflight still does not authorize DB apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_evidence_execution_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out authorization evidence execution readiness without executing it."""
    preflight = build_pchome_auto_policy_db_apply_authorization_evidence_execution_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    verifier_handoff = (
        preflight.get("future_database_apply_authorization_verifier_handoff") or {}
    )
    execution_preflight = (
        preflight.get("authorization_evidence_execution_preflight") or {}
    )
    preflight_contract = (
        preflight.get("authorization_evidence_execution_preflight_contract") or {}
    )
    summary = preflight.get("summary") or {}
    safety = preflight.get("safety") or {}
    closeout_id = _db_apply_authorization_evidence_execution_closeout_id(preflight)
    execution_fields = list(
        execution_preflight.get("authorization_evidence_execution_fields") or []
    )
    execution_acceptance_gates = list(
        execution_preflight.get("authorization_evidence_execution_acceptance_gates") or []
    )
    verifier_receipt_fields = list(
        execution_preflight.get("verifier_receipt_fields") or []
    )
    verifier_receipt_acceptance_gates = list(
        execution_preflight.get("verifier_receipt_acceptance_gates") or []
    )
    handoff_fields = list(
        execution_preflight.get("verifier_receipt_evidence_handoff_fields") or []
    )
    handoff_acceptance_gates = list(
        execution_preflight.get("verifier_receipt_handoff_acceptance_gates") or []
    )
    closeout_fields = [
        "closeout_id",
        "source_authorization_evidence_execution_preflight_id",
        "source_verifier_receipt_closeout_id",
        "source_verifier_receipt_evidence_handoff_id",
        "source_final_signable_request_package_id",
        "verifier_receipt_id_reference",
        "external_receipt_id_reference",
        "payload_sha256",
        "receipt_sha256",
        "verifier_receipt_sha256",
        "final_verifier_gate_endpoint",
        "post_apply_verifier_endpoint",
    ]
    closeout_acceptance_gates = [
        "authorization_evidence_execution_preflight_ready",
        "final_verifier_handoff_ready",
        "source_chain_ids_match",
        "production_truth_same_run_required",
        "payload_receipt_verifier_hashes_present",
        "final_signable_request_package_hash_locked",
        "post_apply_verifier_required",
        "no_secret_signature_or_execution_closeout",
        "no_database_apply_authorized_by_closeout",
        "exception_only_failure_routing",
    ]
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("performs_detached_signature_verification") is False
        and safety.get("persists_verifier_receipt") is False
        and safety.get("executes_authorization_evidence") is False
        and execution_preflight.get("detached_signature_verification_performed") is False
        and execution_preflight.get("verifier_receipt_persisted") is False
        and execution_preflight.get("external_signed_authorization_receipt_included") is False
        and execution_preflight.get("signed_authorization_receipt_included") is False
        and execution_preflight.get("signature_material_included") is False
        and execution_preflight.get("secret_material_included") is False
        and execution_preflight.get("secret_material_required_in_preview") is False
        and execution_preflight.get("accepts_plaintext_secret") is False
        and execution_preflight.get("reads_secret_in_preview") is False
        and execution_preflight.get("executes_shell_in_preview") is False
        and execution_preflight.get("executes_sql_in_preview") is False
        and execution_preflight.get("writes_database_in_preview") is False
        and execution_preflight.get("executes_authorization_evidence") is False
    )
    hashes_present = (
        bool(execution_preflight.get("expected_sha256"))
        and bool(execution_preflight.get("actual_sha256"))
        and execution_preflight.get("hash_matches") is True
        and "payload_sha256" in execution_fields
        and "receipt_sha256" in execution_fields
        and "verifier_receipt_sha256" in execution_fields
    )
    checks = [
        _authorization_evidence_execution_closeout_check(
            "authorization_evidence_execution_preflight_ready",
            preflight.get("result")
            == "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_READY"
            and execution_preflight.get(
                "ready_for_future_authorization_evidence_execution_preflight"
            )
            is True,
            {
                "result": preflight.get("result"),
                "ready_for_future_authorization_evidence_execution_preflight": (
                    execution_preflight.get(
                        "ready_for_future_authorization_evidence_execution_preflight"
                    )
                ),
            },
            "wait_for_authorization_evidence_execution_preflight",
        ),
        _authorization_evidence_execution_closeout_check(
            "final_verifier_handoff_ready",
            verifier_handoff.get(
                "ready_for_future_database_apply_authorization_verifier_handoff"
            )
            is True
            and verifier_handoff.get(
                "can_enter_future_authorization_evidence_execution_closeout"
            )
            is True
            and verifier_handoff.get("authorization_evidence_execution_preflight_ready")
            is True,
            {
                "ready_for_future_database_apply_authorization_verifier_handoff": (
                    verifier_handoff.get(
                        "ready_for_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "can_enter_future_authorization_evidence_execution_closeout": (
                    verifier_handoff.get(
                        "can_enter_future_authorization_evidence_execution_closeout"
                    )
                ),
            },
            "wait_for_database_apply_authorization_verifier_handoff",
        ),
        _authorization_evidence_execution_closeout_check(
            "authorization_evidence_execution_preflight_package_complete",
            execution_preflight.get("authorization_material_type")
            == "authorization_evidence_execution_preflight"
            and bool(execution_preflight.get("preflight_id"))
            and len(execution_fields) == 12
            and len(execution_acceptance_gates) == 10
            and execution_preflight.get("ready_for_database_apply_now") is False
            and execution_preflight.get("issues_database_apply_authorization") is False
            and execution_preflight.get("signs_database_apply_authorization") is False,
            {
                "preflight_id": execution_preflight.get("preflight_id"),
                "authorization_evidence_execution_field_count": len(execution_fields),
                "authorization_evidence_execution_acceptance_gate_count": len(
                    execution_acceptance_gates
                ),
            },
            "wait_for_authorization_evidence_execution_preflight_package",
        ),
        _authorization_evidence_execution_closeout_check(
            "source_chain_ids_present",
            bool(execution_preflight.get("source_verifier_receipt_closeout_id"))
            and bool(execution_preflight.get("source_verifier_receipt_evidence_handoff_id"))
            and bool(
                execution_preflight.get(
                    "source_detached_verification_evidence_validation_id"
                )
            )
            and bool(execution_preflight.get("source_signed_receipt_evidence_intake_id"))
            and bool(execution_preflight.get("source_final_signable_request_package_id")),
            {
                "source_verifier_receipt_closeout_id": execution_preflight.get(
                    "source_verifier_receipt_closeout_id"
                ),
                "source_verifier_receipt_evidence_handoff_id": (
                    execution_preflight.get("source_verifier_receipt_evidence_handoff_id")
                ),
                "source_final_signable_request_package_id": execution_preflight.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _authorization_evidence_execution_closeout_check(
            "authorization_evidence_execution_closeout_contract_complete",
            len(closeout_fields) == 12
            and len(closeout_acceptance_gates) == 10
            and "final_verifier_gate_endpoint" in closeout_fields
            and "no_database_apply_authorized_by_closeout"
            in closeout_acceptance_gates,
            {
                "authorization_evidence_execution_closeout_field_count": len(
                    closeout_fields
                ),
                "authorization_evidence_execution_closeout_acceptance_gate_count": len(
                    closeout_acceptance_gates
                ),
            },
            "wait_for_authorization_evidence_execution_closeout_contract",
        ),
        _authorization_evidence_execution_closeout_check(
            "verifier_receipt_handoff_contract_carried_forward",
            len(verifier_receipt_fields) == 12
            and len(verifier_receipt_acceptance_gates) == 10
            and len(handoff_fields) == 12
            and len(handoff_acceptance_gates) == 10
            and int(summary.get("verifier_receipt_field_count") or 0) == 12
            and int(summary.get("verifier_receipt_handoff_acceptance_gate_count") or 0)
            == 10,
            {
                "verifier_receipt_field_count": len(verifier_receipt_fields),
                "verifier_receipt_acceptance_gate_count": len(
                    verifier_receipt_acceptance_gates
                ),
                "verifier_receipt_evidence_handoff_field_count": len(handoff_fields),
                "verifier_receipt_handoff_acceptance_gate_count": len(
                    handoff_acceptance_gates
                ),
            },
            "wait_for_verifier_receipt_handoff_contract",
        ),
        _authorization_evidence_execution_closeout_check(
            "verifier_hash_and_receipt_chain_locked",
            hashes_present,
            {
                "hash_matches": execution_preflight.get("hash_matches"),
                "expected_sha256_present": bool(execution_preflight.get("expected_sha256")),
                "actual_sha256_present": bool(execution_preflight.get("actual_sha256")),
                "payload_sha256_field_present": "payload_sha256" in execution_fields,
                "receipt_sha256_field_present": "receipt_sha256" in execution_fields,
                "verifier_receipt_sha256_field_present": (
                    "verifier_receipt_sha256" in execution_fields
                ),
            },
            "require_payload_receipt_and_verifier_hash_lock",
        ),
        _authorization_evidence_execution_closeout_check(
            "same_run_production_truth_and_post_apply_verifier_required",
            execution_preflight.get("requires_fresh_production_truth_in_same_run")
            is True
            and execution_preflight.get("requires_post_apply_verifier") is True
            and bool(execution_preflight.get("post_apply_verifier_endpoint"))
            and int(summary.get("same_run_truth_required_count") or 0) == 1
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": (
                    execution_preflight.get("requires_fresh_production_truth_in_same_run")
                ),
                "requires_post_apply_verifier": execution_preflight.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": execution_preflight.get(
                    "post_apply_verifier_endpoint"
                ),
            },
            "require_same_run_production_truth_and_post_apply_verifier",
        ),
        _authorization_evidence_execution_closeout_check(
            "secret_signed_material_and_execution_boundary_enforced",
            execution_preflight.get("detached_signature_verification_performed") is False
            and execution_preflight.get("verifier_receipt_persisted") is False
            and execution_preflight.get("external_signed_authorization_receipt_included")
            is False
            and execution_preflight.get("signed_authorization_receipt_included") is False
            and execution_preflight.get("signature_material_included") is False
            and execution_preflight.get("secret_material_included") is False
            and execution_preflight.get("accepts_plaintext_secret") is False
            and execution_preflight.get("executes_authorization_evidence") is False
            and verifier_handoff.get("executes_authorization_evidence") is False,
            {
                "detached_signature_verification_performed": execution_preflight.get(
                    "detached_signature_verification_performed"
                ),
                "verifier_receipt_persisted": execution_preflight.get(
                    "verifier_receipt_persisted"
                ),
                "signature_material_included": execution_preflight.get(
                    "signature_material_included"
                ),
                "secret_material_included": execution_preflight.get(
                    "secret_material_included"
                ),
                "executes_authorization_evidence": execution_preflight.get(
                    "executes_authorization_evidence"
                ),
            },
            "abort_on_secret_signed_material_execution_or_persistence",
        ),
        _authorization_evidence_execution_closeout_check(
            "preflight_contract_blocks_database_apply",
            preflight_contract.get(
                "permits_future_authorization_evidence_execution_closeout"
            )
            is True
            and preflight_contract.get("issues_database_apply_authorization") is False
            and preflight_contract.get("ready_for_database_apply_now") is False
            and preflight_contract.get("signs_database_apply_authorization") is False
            and preflight_contract.get("writes_database") is False
            and preflight_contract.get("executes_authorization_evidence") is False,
            {
                "permits_future_authorization_evidence_execution_closeout": (
                    preflight_contract.get(
                        "permits_future_authorization_evidence_execution_closeout"
                    )
                ),
                "ready_for_database_apply_now": preflight_contract.get(
                    "ready_for_database_apply_now"
                ),
                "executes_authorization_evidence": preflight_contract.get(
                    "executes_authorization_evidence"
                ),
            },
            "abort_if_preflight_contract_authorizes_database_apply",
        ),
        _authorization_evidence_execution_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "executes_authorization_evidence": safety.get(
                    "executes_authorization_evidence"
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _authorization_evidence_execution_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and verifier_handoff.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(
                    LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0
                ),
                "manual_review_mode": verifier_handoff.get("manual_review_mode"),
            },
            "route_failed_final_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT"
    )
    final_verifier_gate_endpoint = (
        "/api/ai/pchome-growth/mapping-backlog/"
        "auto-policy-db-apply-authorization-evidence-execution-closeout"
    )
    future_database_apply_authorization_final_verifier_gate = {
        "final_verifier_gate_id": closeout_id,
        "source_authorization_evidence_execution_preflight_id": (
            execution_preflight.get("preflight_id")
        ),
        "source_verifier_receipt_closeout_id": execution_preflight.get(
            "source_verifier_receipt_closeout_id"
        ),
        "source_verifier_receipt_evidence_handoff_id": execution_preflight.get(
            "source_verifier_receipt_evidence_handoff_id"
        ),
        "source_final_signable_request_package_id": execution_preflight.get(
            "source_final_signable_request_package_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_authorization_final_verifier_gate": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_apply_final_preflight": (
            closeout_ready
        ),
        "authorization_evidence_execution_closeout_ready": closeout_ready,
        "final_verifier_gate_ready": closeout_ready,
        "final_verifier_gate_executed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    authorization_evidence_execution_closeout = {
        "closeout_id": closeout_id,
        "authorization_material_type": "authorization_evidence_execution_closeout",
        "source_authorization_evidence_execution_preflight_id": (
            execution_preflight.get("preflight_id")
        ),
        "source_verifier_receipt_closeout_id": execution_preflight.get(
            "source_verifier_receipt_closeout_id"
        ),
        "source_verifier_receipt_evidence_handoff_id": execution_preflight.get(
            "source_verifier_receipt_evidence_handoff_id"
        ),
        "source_detached_verification_evidence_validation_id": (
            execution_preflight.get(
                "source_detached_verification_evidence_validation_id"
            )
        ),
        "source_signed_receipt_evidence_intake_id": execution_preflight.get(
            "source_signed_receipt_evidence_intake_id"
        ),
        "source_final_signable_request_package_id": execution_preflight.get(
            "source_final_signable_request_package_id"
        ),
        "status": closeout_status,
        "ready_for_future_authorization_evidence_execution_closeout": (
            closeout_ready
        ),
        "final_verifier_gate_endpoint": final_verifier_gate_endpoint,
        "authorization_evidence_execution_closeout_fields": closeout_fields,
        "authorization_evidence_execution_closeout_field_count": len(closeout_fields),
        "authorization_evidence_execution_closeout_acceptance_gates": (
            closeout_acceptance_gates
        ),
        "authorization_evidence_execution_closeout_acceptance_gate_count": len(
            closeout_acceptance_gates
        ),
        "authorization_evidence_execution_fields": execution_fields,
        "authorization_evidence_execution_field_count": len(execution_fields),
        "authorization_evidence_execution_acceptance_gates": (
            execution_acceptance_gates
        ),
        "authorization_evidence_execution_acceptance_gate_count": len(
            execution_acceptance_gates
        ),
        "verifier_receipt_fields": verifier_receipt_fields,
        "verifier_receipt_field_count": len(verifier_receipt_fields),
        "verifier_receipt_acceptance_gates": verifier_receipt_acceptance_gates,
        "verifier_receipt_acceptance_gate_count": len(
            verifier_receipt_acceptance_gates
        ),
        "verifier_receipt_evidence_handoff_fields": handoff_fields,
        "verifier_receipt_evidence_handoff_field_count": len(handoff_fields),
        "verifier_receipt_handoff_acceptance_gates": handoff_acceptance_gates,
        "verifier_receipt_handoff_acceptance_gate_count": len(
            handoff_acceptance_gates
        ),
        "requires_detached_signature_verification": True,
        "detached_signature_verification_performed": False,
        "verifier_receipt_persisted": False,
        "external_signed_authorization_receipt_required_in_future": True,
        "external_signed_authorization_receipt_included": False,
        "signed_authorization_receipt_included": False,
        "signature_material_included": False,
        "signer_key_id_reference_only": True,
        "signature_algorithm_reference_only": True,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "target_file": execution_preflight.get("target_file"),
        "expected_sha256": execution_preflight.get("expected_sha256"),
        "actual_sha256": execution_preflight.get("actual_sha256"),
        "hash_matches": execution_preflight.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": execution_preflight.get(
            "post_apply_verifier_endpoint"
        ),
    }
    authorization_evidence_execution_closeout_contract = {
        "mode": "authorization_evidence_execution_closeout_final_verifier_gate_only",
        "source_endpoint": final_verifier_gate_endpoint,
        "source_authorization_evidence_execution_preflight_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-authorization-evidence-execution-preflight"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_authorization_final_verifier_gate": closeout_ready,
        "permits_future_database_apply_controlled_apply_final_preflight": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(preflight.get("success")),
        "generated_at": preflight.get("generated_at"),
        "source_policy": preflight.get("policy"),
        "stats": preflight.get("stats") or {},
        "summary": {
            "authorization_evidence_execution_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "authorization_evidence_execution_closeout_check_count": len(checks),
            "authorization_evidence_execution_closeout_pass_count": passed_count,
            "authorization_evidence_execution_closeout_waiting_count": len(
                waiting_checks
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "authorization_verifier_receipt_closeout_ready_count": summary.get(
                "authorization_verifier_receipt_closeout_ready_count", 0
            ),
            "verifier_receipt_closeout_check_count": summary.get(
                "verifier_receipt_closeout_check_count", 0
            ),
            "authorization_detached_verification_evidence_validation_ready_count": (
                summary.get(
                    "authorization_detached_verification_evidence_validation_ready_count",
                    0,
                )
            ),
            "detached_verification_evidence_validation_check_count": summary.get(
                "detached_verification_evidence_validation_check_count", 0
            ),
            "verifier_receipt_evidence_handoff_count": summary.get(
                "verifier_receipt_evidence_handoff_count", 0
            ),
            "authorization_evidence_execution_preflight_count": summary.get(
                "authorization_evidence_execution_preflight_count", 0
            ),
            "authorization_evidence_execution_closeout_count": 1,
            "database_apply_final_verifier_gate_count": 1,
            "database_apply_authorization_final_verifier_gate_ready_count": (
                1 if closeout_ready else 0
            ),
            "authorization_evidence_execution_closeout_field_count": len(
                closeout_fields
            ),
            "authorization_evidence_execution_closeout_acceptance_gate_count": len(
                closeout_acceptance_gates
            ),
            "authorization_evidence_execution_field_count": summary.get(
                "authorization_evidence_execution_field_count", 0
            ),
            "authorization_evidence_execution_acceptance_gate_count": summary.get(
                "authorization_evidence_execution_acceptance_gate_count", 0
            ),
            "verifier_receipt_field_count": summary.get(
                "verifier_receipt_field_count", 0
            ),
            "verifier_receipt_acceptance_gate_count": summary.get(
                "verifier_receipt_acceptance_gate_count", 0
            ),
            "verifier_receipt_evidence_handoff_field_count": summary.get(
                "verifier_receipt_evidence_handoff_field_count", 0
            ),
            "verifier_receipt_handoff_acceptance_gate_count": summary.get(
                "verifier_receipt_handoff_acceptance_gate_count", 0
            ),
            "required_external_receipt_evidence_count": summary.get(
                "required_external_receipt_evidence_count", 0
            ),
            "external_receipt_acceptance_gate_count": summary.get(
                "external_receipt_acceptance_gate_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_authorization_final_verifier_gate": (
            future_database_apply_authorization_final_verifier_gate
        ),
        "authorization_evidence_execution_closeout": (
            authorization_evidence_execution_closeout
        ),
        "authorization_evidence_execution_closeout_contract": (
            authorization_evidence_execution_closeout_contract
        ),
        "authorization_evidence_execution_closeout_checks": checks,
        "source_authorization_evidence_execution_preflight_summary": summary,
        "source_authorization_evidence_execution_preflight_contract": (
            preflight_contract
        ),
        "source_authorization_evidence_execution_preflight": execution_preflight,
        "source_database_apply_authorization_verifier_handoff": verifier_handoff,
        "safety": {
            "read_only_db_apply_authorization_evidence_execution_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the final verifier gate input for a future controlled-apply final preflight.",
            "Keep signed receipt body, signature material, secret values, endpoint execution, SQL, and DB writes out of this closeout.",
            "A later controlled-apply final preflight may bind rollback and post-apply verification; this closeout still does not authorize DB apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_apply_final_preflight(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Bind rollback and verifier requirements before any controlled apply."""
    closeout = build_pchome_auto_policy_db_apply_authorization_evidence_execution_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    final_gate = (
        closeout.get("future_database_apply_authorization_final_verifier_gate") or {}
    )
    evidence_closeout = closeout.get("authorization_evidence_execution_closeout") or {}
    closeout_contract = (
        closeout.get("authorization_evidence_execution_closeout_contract") or {}
    )
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    preflight_id = _db_apply_controlled_apply_final_preflight_id(closeout)
    controlled_apply_fields = [
        "controlled_apply_preflight_id",
        "source_final_verifier_gate_id",
        "source_authorization_evidence_execution_closeout_id",
        "source_final_signable_request_package_id",
        "target_migration_file",
        "target_migration_sha256",
        "rollback_binding_id",
        "rollback_verifier_endpoint",
        "post_apply_verifier_endpoint",
        "same_run_production_truth_reference",
        "dry_run_command_shape",
        "abort_conditions",
    ]
    controlled_apply_acceptance_gates = [
        "final_verifier_gate_ready",
        "source_chain_ids_match",
        "target_migration_hash_locked",
        "rollback_plan_bound",
        "post_apply_verifier_bound",
        "same_run_production_truth_required",
        "dry_run_only_no_execution",
        "no_secret_signature_or_database_apply",
        "database_write_gate_remains_closed",
        "exception_only_failure_routing",
    ]
    rollback_binding_fields = [
        "rollback_binding_id",
        "target_migration_file",
        "target_migration_sha256",
        "rollback_strategy",
        "rollback_verifier_endpoint",
        "post_apply_verifier_endpoint",
        "rollback_requires_same_run_truth",
        "rollback_execution_authorized",
    ]
    post_apply_verifier_binding_fields = [
        "post_apply_verifier_binding_id",
        "source_final_verifier_gate_id",
        "post_apply_verifier_endpoint",
        "expected_migration_sha256",
        "same_run_production_truth_required",
        "verifier_must_run_after_apply",
        "verifier_execution_authorized_in_preview",
        "database_apply_authorized",
    ]
    target_file = evidence_closeout.get("target_file")
    expected_sha256 = evidence_closeout.get("expected_sha256")
    actual_sha256 = evidence_closeout.get("actual_sha256")
    target_hash_locked = (
        target_file == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(expected_sha256)
        and bool(actual_sha256)
        and expected_sha256 == actual_sha256
        and evidence_closeout.get("hash_matches") is True
    )
    rollback_binding_id = f"{preflight_id}-rollback"
    post_apply_verifier_binding_id = f"{preflight_id}-post-apply-verifier"
    rollback_binding = {
        "rollback_binding_id": rollback_binding_id,
        "target_migration_file": target_file,
        "target_migration_sha256": expected_sha256,
        "rollback_strategy": "fail_closed_no_apply_without_post_apply_verifier",
        "rollback_verifier_endpoint": evidence_closeout.get("post_apply_verifier_endpoint"),
        "post_apply_verifier_endpoint": evidence_closeout.get("post_apply_verifier_endpoint"),
        "rollback_requires_same_run_truth": True,
        "rollback_execution_authorized": False,
        "rollback_executes_sql": False,
        "rollback_writes_database": False,
        "rollback_reads_secret": False,
        "rollback_binding_field_count": len(rollback_binding_fields),
        "rollback_binding_fields": rollback_binding_fields,
    }
    post_apply_verifier_binding = {
        "post_apply_verifier_binding_id": post_apply_verifier_binding_id,
        "source_final_verifier_gate_id": final_gate.get("final_verifier_gate_id"),
        "post_apply_verifier_endpoint": evidence_closeout.get("post_apply_verifier_endpoint"),
        "expected_migration_sha256": expected_sha256,
        "same_run_production_truth_required": True,
        "verifier_must_run_after_apply": True,
        "verifier_execution_authorized_in_preview": False,
        "database_apply_authorized": False,
        "post_apply_verifier_binding_field_count": len(
            post_apply_verifier_binding_fields
        ),
        "post_apply_verifier_binding_fields": post_apply_verifier_binding_fields,
    }
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("performs_detached_signature_verification") is False
        and safety.get("persists_verifier_receipt") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and evidence_closeout.get("detached_signature_verification_performed") is False
        and evidence_closeout.get("verifier_receipt_persisted") is False
        and evidence_closeout.get("external_signed_authorization_receipt_included")
        is False
        and evidence_closeout.get("signed_authorization_receipt_included") is False
        and evidence_closeout.get("signature_material_included") is False
        and evidence_closeout.get("secret_material_included") is False
        and evidence_closeout.get("secret_material_required_in_preview") is False
        and evidence_closeout.get("accepts_plaintext_secret") is False
        and evidence_closeout.get("reads_secret_in_preview") is False
        and evidence_closeout.get("executes_shell_in_preview") is False
        and evidence_closeout.get("executes_endpoint_in_preview") is False
        and evidence_closeout.get("executes_sql_in_preview") is False
        and evidence_closeout.get("writes_database_in_preview") is False
        and evidence_closeout.get("executes_authorization_evidence") is False
        and evidence_closeout.get("executes_database_apply") is False
    )
    checks = [
        _controlled_apply_final_preflight_check(
            "final_verifier_gate_ready",
            closeout.get("result")
            == "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_READY"
            and final_gate.get(
                "ready_for_future_database_apply_authorization_final_verifier_gate"
            )
            is True
            and final_gate.get(
                "can_enter_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and evidence_closeout.get(
                "ready_for_future_authorization_evidence_execution_closeout"
            )
            is True,
            {
                "result": closeout.get("result"),
                "ready_for_future_database_apply_authorization_final_verifier_gate": (
                    final_gate.get(
                        "ready_for_future_database_apply_authorization_final_verifier_gate"
                    )
                ),
                "can_enter_future_database_apply_controlled_apply_final_preflight": (
                    final_gate.get(
                        "can_enter_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
            },
            "wait_for_database_apply_authorization_final_verifier_gate",
        ),
        _controlled_apply_final_preflight_check(
            "authorization_evidence_execution_closeout_package_complete",
            evidence_closeout.get("authorization_material_type")
            == "authorization_evidence_execution_closeout"
            and bool(evidence_closeout.get("closeout_id"))
            and int(
                evidence_closeout.get(
                    "authorization_evidence_execution_closeout_field_count"
                )
                or 0
            )
            == 12
            and int(
                evidence_closeout.get(
                    "authorization_evidence_execution_closeout_acceptance_gate_count"
                )
                or 0
            )
            == 10
            and evidence_closeout.get("ready_for_database_apply_now") is False
            and evidence_closeout.get("database_apply_authorized") is False,
            {
                "closeout_id": evidence_closeout.get("closeout_id"),
                "authorization_evidence_execution_closeout_field_count": (
                    evidence_closeout.get(
                        "authorization_evidence_execution_closeout_field_count"
                    )
                ),
                "authorization_evidence_execution_closeout_acceptance_gate_count": (
                    evidence_closeout.get(
                        "authorization_evidence_execution_closeout_acceptance_gate_count"
                    )
                ),
            },
            "wait_for_authorization_evidence_execution_closeout_package",
        ),
        _controlled_apply_final_preflight_check(
            "source_chain_ids_present",
            bool(final_gate.get("final_verifier_gate_id"))
            and bool(evidence_closeout.get("closeout_id"))
            and bool(evidence_closeout.get("source_authorization_evidence_execution_preflight_id"))
            and bool(evidence_closeout.get("source_verifier_receipt_closeout_id"))
            and bool(evidence_closeout.get("source_verifier_receipt_evidence_handoff_id"))
            and bool(evidence_closeout.get("source_final_signable_request_package_id")),
            {
                "final_verifier_gate_id": final_gate.get("final_verifier_gate_id"),
                "closeout_id": evidence_closeout.get("closeout_id"),
                "source_final_signable_request_package_id": evidence_closeout.get(
                    "source_final_signable_request_package_id"
                ),
            },
            "wait_for_source_authorization_chain_ids",
        ),
        _controlled_apply_final_preflight_check(
            "controlled_apply_final_preflight_contract_complete",
            len(controlled_apply_fields) == 12
            and len(controlled_apply_acceptance_gates) == 10
            and "rollback_binding_id" in controlled_apply_fields
            and "post_apply_verifier_bound" in controlled_apply_acceptance_gates,
            {
                "controlled_apply_final_preflight_field_count": len(
                    controlled_apply_fields
                ),
                "controlled_apply_final_preflight_acceptance_gate_count": len(
                    controlled_apply_acceptance_gates
                ),
            },
            "wait_for_controlled_apply_final_preflight_contract",
        ),
        _controlled_apply_final_preflight_check(
            "rollback_binding_complete",
            len(rollback_binding_fields) == 8
            and bool(rollback_binding.get("rollback_binding_id"))
            and rollback_binding.get("rollback_requires_same_run_truth") is True
            and rollback_binding.get("rollback_execution_authorized") is False
            and rollback_binding.get("rollback_executes_sql") is False
            and rollback_binding.get("rollback_writes_database") is False,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "rollback_binding_field_count": len(rollback_binding_fields),
                "rollback_execution_authorized": rollback_binding.get(
                    "rollback_execution_authorized"
                ),
            },
            "wait_for_rollback_binding",
        ),
        _controlled_apply_final_preflight_check(
            "post_apply_verifier_binding_complete",
            len(post_apply_verifier_binding_fields) == 8
            and bool(post_apply_verifier_binding.get("post_apply_verifier_binding_id"))
            and bool(post_apply_verifier_binding.get("post_apply_verifier_endpoint"))
            and post_apply_verifier_binding.get("same_run_production_truth_required")
            is True
            and post_apply_verifier_binding.get("verifier_must_run_after_apply")
            is True
            and post_apply_verifier_binding.get("verifier_execution_authorized_in_preview")
            is False
            and post_apply_verifier_binding.get("database_apply_authorized") is False,
            {
                "post_apply_verifier_binding_id": post_apply_verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "post_apply_verifier_endpoint": post_apply_verifier_binding.get(
                    "post_apply_verifier_endpoint"
                ),
                "post_apply_verifier_binding_field_count": len(
                    post_apply_verifier_binding_fields
                ),
            },
            "wait_for_post_apply_verifier_binding",
        ),
        _controlled_apply_final_preflight_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": target_file,
                "expected_sha256_present": bool(expected_sha256),
                "actual_sha256_present": bool(actual_sha256),
                "hash_matches": evidence_closeout.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_apply_final_preflight_check(
            "same_run_production_truth_and_post_apply_verifier_required",
            evidence_closeout.get("requires_fresh_production_truth_in_same_run") is True
            and evidence_closeout.get("requires_post_apply_verifier") is True
            and bool(evidence_closeout.get("post_apply_verifier_endpoint"))
            and int(summary.get("same_run_truth_required_count") or 0) == 1
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": evidence_closeout.get(
                    "requires_fresh_production_truth_in_same_run"
                ),
                "requires_post_apply_verifier": evidence_closeout.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": evidence_closeout.get(
                    "post_apply_verifier_endpoint"
                ),
            },
            "require_same_run_production_truth_and_post_apply_verifier",
        ),
        _controlled_apply_final_preflight_check(
            "secret_signed_material_execution_and_write_boundary_enforced",
            evidence_closeout.get("detached_signature_verification_performed") is False
            and evidence_closeout.get("verifier_receipt_persisted") is False
            and evidence_closeout.get("external_signed_authorization_receipt_included")
            is False
            and evidence_closeout.get("signed_authorization_receipt_included") is False
            and evidence_closeout.get("signature_material_included") is False
            and evidence_closeout.get("secret_material_included") is False
            and evidence_closeout.get("accepts_plaintext_secret") is False
            and evidence_closeout.get("executes_authorization_evidence") is False
            and evidence_closeout.get("executes_database_apply") is False
            and final_gate.get("database_apply_authorized") is False,
            {
                "signature_material_included": evidence_closeout.get(
                    "signature_material_included"
                ),
                "secret_material_included": evidence_closeout.get(
                    "secret_material_included"
                ),
                "executes_database_apply": evidence_closeout.get(
                    "executes_database_apply"
                ),
                "database_apply_authorized": final_gate.get(
                    "database_apply_authorized"
                ),
            },
            "abort_on_secret_signed_material_execution_or_write_boundary_violation",
        ),
        _controlled_apply_final_preflight_check(
            "final_verifier_contract_blocks_database_apply",
            closeout_contract.get(
                "permits_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and closeout_contract.get("executes_database_apply") is False
            and closeout_contract.get("database_apply_authorized") is False
            and closeout_contract.get("ready_for_database_apply_now") is False
            and closeout_contract.get("signs_database_apply_authorization") is False
            and closeout_contract.get("writes_database") is False,
            {
                "permits_future_database_apply_controlled_apply_final_preflight": (
                    closeout_contract.get(
                        "permits_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "database_apply_authorized": closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": closeout_contract.get("writes_database"),
            },
            "abort_if_final_verifier_contract_authorizes_database_apply",
        ),
        _controlled_apply_final_preflight_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "executes_database_apply": safety.get("executes_database_apply"),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_apply_final_preflight_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and final_gate.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(
                    LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0
                ),
                "manual_review_mode": final_gate.get("manual_review_mode"),
            },
            "route_failed_controlled_apply_preflight_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    final_preflight_ready = not waiting_checks
    final_preflight_status = (
        "DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_READY"
        if final_preflight_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT"
    )
    future_database_apply_controlled_apply_final_preflight = {
        "controlled_apply_preflight_id": preflight_id,
        "source_final_verifier_gate_id": final_gate.get("final_verifier_gate_id"),
        "source_authorization_evidence_execution_closeout_id": (
            evidence_closeout.get("closeout_id")
        ),
        "source_authorization_evidence_execution_preflight_id": (
            evidence_closeout.get("source_authorization_evidence_execution_preflight_id")
        ),
        "source_final_signable_request_package_id": evidence_closeout.get(
            "source_final_signable_request_package_id"
        ),
        "status": final_preflight_status,
        "ready_for_future_database_apply_controlled_apply_final_preflight": (
            final_preflight_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_package": (
            final_preflight_ready
        ),
        "controlled_apply_final_preflight_ready": final_preflight_ready,
        "rollback_binding_ready": final_preflight_ready,
        "post_apply_verifier_binding_ready": final_preflight_ready,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_apply_final_preflight = {
        "controlled_apply_preflight_id": preflight_id,
        "authorization_material_type": "controlled_apply_final_preflight",
        "source_final_verifier_gate_id": final_gate.get("final_verifier_gate_id"),
        "source_authorization_evidence_execution_closeout_id": (
            evidence_closeout.get("closeout_id")
        ),
        "source_authorization_evidence_execution_preflight_id": (
            evidence_closeout.get("source_authorization_evidence_execution_preflight_id")
        ),
        "source_verifier_receipt_closeout_id": evidence_closeout.get(
            "source_verifier_receipt_closeout_id"
        ),
        "source_verifier_receipt_evidence_handoff_id": evidence_closeout.get(
            "source_verifier_receipt_evidence_handoff_id"
        ),
        "source_final_signable_request_package_id": evidence_closeout.get(
            "source_final_signable_request_package_id"
        ),
        "status": final_preflight_status,
        "ready_for_future_database_apply_controlled_apply_final_preflight": (
            final_preflight_ready
        ),
        "controlled_apply_final_preflight_fields": controlled_apply_fields,
        "controlled_apply_final_preflight_field_count": len(controlled_apply_fields),
        "controlled_apply_final_preflight_acceptance_gates": (
            controlled_apply_acceptance_gates
        ),
        "controlled_apply_final_preflight_acceptance_gate_count": len(
            controlled_apply_acceptance_gates
        ),
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "rollback_binding_field_count": len(rollback_binding_fields),
        "post_apply_verifier_binding": post_apply_verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "post_apply_verifier_binding_field_count": len(
            post_apply_verifier_binding_fields
        ),
        "target_file": target_file,
        "expected_sha256": expected_sha256,
        "actual_sha256": actual_sha256,
        "hash_matches": evidence_closeout.get("hash_matches"),
        "dry_run_only": True,
        "check_mode_only": True,
        "rollback_bound": final_preflight_ready,
        "post_apply_verifier_bound": final_preflight_ready,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "post_apply_verifier_endpoint": evidence_closeout.get(
            "post_apply_verifier_endpoint"
        ),
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "secret_material_required_in_preview": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
    }
    controlled_apply_final_preflight_contract = {
        "mode": "controlled_apply_final_preflight_rollback_and_verifier_binding_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-apply-final-preflight"
        ),
        "source_authorization_evidence_execution_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-authorization-evidence-execution-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_package": (
            final_preflight_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_POLICY,
        "result": final_preflight_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "controlled_apply_final_preflight_ready_count": (
                1 if final_preflight_ready else 0
            ),
            "controlled_apply_final_preflight_check_count": len(checks),
            "controlled_apply_final_preflight_pass_count": passed_count,
            "controlled_apply_final_preflight_waiting_count": len(waiting_checks),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "authorization_verifier_receipt_closeout_ready_count": summary.get(
                "authorization_verifier_receipt_closeout_ready_count", 0
            ),
            "verifier_receipt_closeout_check_count": summary.get(
                "verifier_receipt_closeout_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": summary.get(
                "database_apply_authorization_final_verifier_gate_ready_count", 0
            ),
            "controlled_apply_final_preflight_count": 1,
            "rollback_binding_count": 1,
            "rollback_binding_field_count": len(rollback_binding_fields),
            "post_apply_verifier_binding_count": 1,
            "post_apply_verifier_binding_field_count": len(
                post_apply_verifier_binding_fields
            ),
            "controlled_apply_final_preflight_field_count": len(
                controlled_apply_fields
            ),
            "controlled_apply_final_preflight_acceptance_gate_count": len(
                controlled_apply_acceptance_gates
            ),
            "authorization_evidence_execution_closeout_field_count": summary.get(
                "authorization_evidence_execution_closeout_field_count", 0
            ),
            "authorization_evidence_execution_closeout_acceptance_gate_count": (
                summary.get(
                    "authorization_evidence_execution_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get("same_run_truth_required_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_apply_final_preflight": (
            future_database_apply_controlled_apply_final_preflight
        ),
        "controlled_apply_final_preflight": controlled_apply_final_preflight,
        "controlled_apply_final_preflight_contract": (
            controlled_apply_final_preflight_contract
        ),
        "controlled_apply_final_preflight_checks": checks,
        "source_authorization_evidence_execution_closeout_summary": summary,
        "source_authorization_evidence_execution_closeout_contract": closeout_contract,
        "source_authorization_evidence_execution_closeout": evidence_closeout,
        "source_database_apply_authorization_final_verifier_gate": final_gate,
        "safety": {
            "read_only_db_apply_controlled_apply_final_preflight": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this final preflight to build a future controlled dry-run package.",
            "Keep rollback and post-apply verifier binding machine-verifiable before any apply execution.",
            "This preflight still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_package(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Package a future controlled dry-run receipt without executing it."""
    final_preflight = build_pchome_auto_policy_db_apply_controlled_apply_final_preflight(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_preflight = (
        final_preflight.get("future_database_apply_controlled_apply_final_preflight")
        or {}
    )
    controlled_preflight = final_preflight.get("controlled_apply_final_preflight") or {}
    final_preflight_contract = (
        final_preflight.get("controlled_apply_final_preflight_contract") or {}
    )
    summary = final_preflight.get("summary") or {}
    safety = final_preflight.get("safety") or {}
    package_id = _db_apply_controlled_dry_run_package_id(final_preflight)
    receipt_id = f"{package_id}-dry-run-receipt-preview"
    rollback_binding = controlled_preflight.get("rollback_binding") or {}
    verifier_binding = controlled_preflight.get("post_apply_verifier_binding") or {}
    target_file = controlled_preflight.get("target_file")
    expected_sha256 = controlled_preflight.get("expected_sha256")
    actual_sha256 = controlled_preflight.get("actual_sha256")
    target_hash_locked = (
        target_file == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(expected_sha256)
        and bool(actual_sha256)
        and expected_sha256 == actual_sha256
        and controlled_preflight.get("hash_matches") is True
    )
    dry_run_package_fields = [
        "dry_run_package_id",
        "source_controlled_apply_preflight_id",
        "source_final_verifier_gate_id",
        "source_authorization_evidence_execution_closeout_id",
        "target_migration_file",
        "target_migration_sha256",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_command_shape",
        "dry_run_result_parser",
        "dry_run_execution_receipt_id",
        "abort_conditions",
    ]
    dry_run_acceptance_gates = [
        "controlled_apply_final_preflight_ready",
        "source_chain_ids_match",
        "rollback_binding_present",
        "post_apply_verifier_binding_present",
        "target_migration_hash_locked",
        "dry_run_command_shape_is_non_executable",
        "dry_run_receipt_preview_only",
        "no_secret_signature_or_database_apply",
        "no_endpoint_sql_or_db_write",
        "exception_only_failure_routing",
    ]
    receipt_fields = [
        "receipt_id",
        "source_dry_run_package_id",
        "dry_run_status",
        "dry_run_command_shape_hash",
        "execution_performed",
        "stdout_included",
        "stderr_included",
        "database_apply_authorized",
    ]
    result_parser_fields = [
        "parser_id",
        "source_dry_run_package_id",
        "expected_receipt_status",
        "required_receipt_fields",
        "required_command_shape_hash",
        "execution_required",
        "stdout_allowed",
        "stderr_allowed",
        "database_apply_authorized",
        "parser_verification_status",
    ]
    command_shape = {
        "command_family": "pchome_db_apply_controlled_dry_run",
        "dry_run_only": True,
        "check_mode_only": True,
        "execution_allowed": False,
        "shell_command_included": False,
        "sql_included": False,
        "endpoint_execution_included": False,
        "database_write_included": False,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_rollback_binding": True,
        "requires_post_apply_verifier_binding": True,
        "target_file": target_file,
        "target_sha256": expected_sha256,
        "args_preview": [
            "--dry-run",
            "--check",
            "--no-execute",
            "--require-post-apply-verifier",
        ],
    }
    command_shape_hash = hashlib.sha256(
        json.dumps(command_shape, sort_keys=True).encode("utf-8")
    ).hexdigest()
    dry_run_execution_receipt_preview = {
        "receipt_id": receipt_id,
        "source_dry_run_package_id": package_id,
        "dry_run_status": "preview_only_not_executed",
        "dry_run_command_shape_hash": command_shape_hash,
        "execution_performed": False,
        "stdout_included": False,
        "stderr_included": False,
        "database_apply_authorized": False,
        "executes_shell": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret": False,
        "receipt_field_count": len(receipt_fields),
        "receipt_fields": receipt_fields,
    }
    dry_run_result_parser = {
        "parser_id": f"{package_id}-result-parser",
        "source_dry_run_package_id": package_id,
        "expected_receipt_status": "preview_only_not_executed",
        "required_receipt_fields": receipt_fields,
        "required_command_shape_hash": command_shape_hash,
        "execution_required": False,
        "stdout_allowed": False,
        "stderr_allowed": False,
        "database_apply_authorized": False,
        "parser_verification_status": "schema_preview_ready",
        "parser_field_count": len(result_parser_fields),
        "parser_fields": result_parser_fields,
    }
    command_shape_preview_only = (
        command_shape.get("dry_run_only") is True
        and command_shape.get("check_mode_only") is True
        and command_shape.get("execution_allowed") is False
        and command_shape.get("shell_command_included") is False
        and command_shape.get("sql_included") is False
        and command_shape.get("endpoint_execution_included") is False
        and command_shape.get("database_write_included") is False
    )
    receipt_preview_only = (
        dry_run_execution_receipt_preview.get("execution_performed") is False
        and dry_run_execution_receipt_preview.get("stdout_included") is False
        and dry_run_execution_receipt_preview.get("stderr_included") is False
        and dry_run_execution_receipt_preview.get("database_apply_authorized") is False
        and dry_run_execution_receipt_preview.get("executes_shell") is False
        and dry_run_execution_receipt_preview.get("executes_endpoint") is False
        and dry_run_execution_receipt_preview.get("executes_sql") is False
        and dry_run_execution_receipt_preview.get("writes_database") is False
        and dry_run_execution_receipt_preview.get("reads_secret") is False
    )
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and controlled_preflight.get("accepts_plaintext_secret") is False
        and controlled_preflight.get("reads_secret_in_preview") is False
        and controlled_preflight.get("signature_material_included") is False
        and controlled_preflight.get("secret_material_included") is False
        and controlled_preflight.get("secret_material_required_in_preview") is False
        and controlled_preflight.get("signs_database_apply_authorization") is False
        and controlled_preflight.get("executes_authorization_evidence") is False
        and controlled_preflight.get("executes_database_apply") is False
        and controlled_preflight.get("executes_endpoint_in_preview") is False
        and controlled_preflight.get("executes_sql_in_preview") is False
        and controlled_preflight.get("writes_database_in_preview") is False
        and command_shape_preview_only
        and receipt_preview_only
    )
    checks = [
        _controlled_dry_run_package_check(
            "controlled_apply_final_preflight_ready",
            final_preflight.get("result")
            == "DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_READY"
            and future_preflight.get(
                "ready_for_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and future_preflight.get(
                "can_enter_future_database_apply_controlled_dry_run_package"
            )
            is True
            and controlled_preflight.get(
                "ready_for_future_database_apply_controlled_apply_final_preflight"
            )
            is True,
            {
                "result": final_preflight.get("result"),
                "ready_for_future_database_apply_controlled_apply_final_preflight": (
                    future_preflight.get(
                        "ready_for_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_package": (
                    future_preflight.get(
                        "can_enter_future_database_apply_controlled_dry_run_package"
                    )
                ),
            },
            "wait_for_controlled_apply_final_preflight",
        ),
        _controlled_dry_run_package_check(
            "source_chain_ids_present",
            bool(future_preflight.get("controlled_apply_preflight_id"))
            and bool(controlled_preflight.get("source_final_verifier_gate_id"))
            and bool(
                controlled_preflight.get(
                    "source_authorization_evidence_execution_closeout_id"
                )
            )
            and bool(
                controlled_preflight.get("source_final_signable_request_package_id")
            ),
            {
                "controlled_apply_preflight_id": future_preflight.get(
                    "controlled_apply_preflight_id"
                ),
                "source_final_verifier_gate_id": controlled_preflight.get(
                    "source_final_verifier_gate_id"
                ),
                "source_authorization_evidence_execution_closeout_id": (
                    controlled_preflight.get(
                        "source_authorization_evidence_execution_closeout_id"
                    )
                ),
            },
            "wait_for_source_controlled_apply_chain_ids",
        ),
        _controlled_dry_run_package_check(
            "controlled_dry_run_package_contract_complete",
            len(dry_run_package_fields) == 12
            and len(dry_run_acceptance_gates) == 10
            and len(receipt_fields) == 8
            and "dry_run_execution_receipt_id" in dry_run_package_fields
            and "dry_run_receipt_preview_only" in dry_run_acceptance_gates,
            {
                "controlled_dry_run_package_field_count": len(
                    dry_run_package_fields
                ),
                "controlled_dry_run_acceptance_gate_count": len(
                    dry_run_acceptance_gates
                ),
                "dry_run_execution_receipt_field_count": len(receipt_fields),
            },
            "wait_for_controlled_dry_run_package_contract",
        ),
        _controlled_dry_run_package_check(
            "rollback_binding_carried_forward",
            bool(rollback_binding.get("rollback_binding_id"))
            and rollback_binding.get("rollback_requires_same_run_truth") is True
            and rollback_binding.get("rollback_execution_authorized") is False
            and rollback_binding.get("rollback_executes_sql") is False
            and rollback_binding.get("rollback_writes_database") is False,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "rollback_execution_authorized": rollback_binding.get(
                    "rollback_execution_authorized"
                ),
                "rollback_executes_sql": rollback_binding.get("rollback_executes_sql"),
            },
            "wait_for_rollback_binding",
        ),
        _controlled_dry_run_package_check(
            "post_apply_verifier_binding_carried_forward",
            bool(verifier_binding.get("post_apply_verifier_binding_id"))
            and bool(verifier_binding.get("post_apply_verifier_endpoint"))
            and verifier_binding.get("same_run_production_truth_required") is True
            and verifier_binding.get("verifier_must_run_after_apply") is True
            and verifier_binding.get("verifier_execution_authorized_in_preview")
            is False
            and verifier_binding.get("database_apply_authorized") is False,
            {
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "post_apply_verifier_endpoint": verifier_binding.get(
                    "post_apply_verifier_endpoint"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_post_apply_verifier_binding",
        ),
        _controlled_dry_run_package_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": target_file,
                "expected_sha256_present": bool(expected_sha256),
                "actual_sha256_present": bool(actual_sha256),
                "hash_matches": controlled_preflight.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_package_check(
            "dry_run_command_shape_preview_only",
            command_shape_preview_only
            and command_shape.get("requires_fresh_production_truth_in_same_run")
            is True
            and command_shape.get("requires_rollback_binding") is True
            and command_shape.get("requires_post_apply_verifier_binding") is True
            and bool(command_shape_hash),
            {
                "dry_run_only": command_shape.get("dry_run_only"),
                "check_mode_only": command_shape.get("check_mode_only"),
                "execution_allowed": command_shape.get("execution_allowed"),
                "dry_run_command_shape_hash_present": bool(command_shape_hash),
            },
            "abort_if_dry_run_command_shape_is_executable",
        ),
        _controlled_dry_run_package_check(
            "dry_run_execution_receipt_preview_only",
            receipt_preview_only
            and dry_run_execution_receipt_preview.get("receipt_field_count") == 8
            and bool(dry_run_execution_receipt_preview.get("receipt_id"))
            and bool(
                dry_run_execution_receipt_preview.get(
                    "dry_run_command_shape_hash"
                )
            ),
            {
                "receipt_id": dry_run_execution_receipt_preview.get("receipt_id"),
                "dry_run_status": dry_run_execution_receipt_preview.get(
                    "dry_run_status"
                ),
                "execution_performed": dry_run_execution_receipt_preview.get(
                    "execution_performed"
                ),
            },
            "abort_if_dry_run_receipt_indicates_execution",
        ),
        _controlled_dry_run_package_check(
            "same_run_production_truth_and_post_apply_verifier_required",
            controlled_preflight.get("requires_fresh_production_truth_in_same_run")
            is True
            and controlled_preflight.get("requires_post_apply_verifier") is True
            and bool(controlled_preflight.get("post_apply_verifier_endpoint"))
            and int(summary.get("same_run_truth_required_count") or 0) == 1
            and int(summary.get("post_apply_verifier_required_count") or 0) == 1,
            {
                "requires_fresh_production_truth_in_same_run": (
                    controlled_preflight.get(
                        "requires_fresh_production_truth_in_same_run"
                    )
                ),
                "requires_post_apply_verifier": controlled_preflight.get(
                    "requires_post_apply_verifier"
                ),
                "post_apply_verifier_endpoint": controlled_preflight.get(
                    "post_apply_verifier_endpoint"
                ),
            },
            "require_same_run_production_truth_and_post_apply_verifier",
        ),
        _controlled_dry_run_package_check(
            "final_preflight_contract_blocks_database_apply",
            final_preflight_contract.get(
                "permits_future_database_apply_controlled_dry_run_package"
            )
            is True
            and final_preflight_contract.get("executes_database_apply") is False
            and final_preflight_contract.get("database_apply_authorized") is False
            and final_preflight_contract.get("ready_for_database_apply_now") is False
            and final_preflight_contract.get("signs_database_apply_authorization")
            is False
            and final_preflight_contract.get("writes_database") is False,
            {
                "permits_future_database_apply_controlled_dry_run_package": (
                    final_preflight_contract.get(
                        "permits_future_database_apply_controlled_dry_run_package"
                    )
                ),
                "database_apply_authorized": final_preflight_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": final_preflight_contract.get("writes_database"),
            },
            "abort_if_final_preflight_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_package_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "command_shape_preview_only": command_shape_preview_only,
                "receipt_preview_only": receipt_preview_only,
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_package_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_preflight.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(
                    LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0
                ),
                "manual_review_mode": future_preflight.get("manual_review_mode"),
            },
            "route_failed_dry_run_package_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    package_ready = not waiting_checks
    package_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_READY"
        if package_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT"
    )
    future_database_apply_controlled_dry_run_execution_receipt = {
        "dry_run_package_id": package_id,
        "dry_run_execution_receipt_id": receipt_id,
        "source_controlled_apply_preflight_id": future_preflight.get(
            "controlled_apply_preflight_id"
        ),
        "source_final_verifier_gate_id": controlled_preflight.get(
            "source_final_verifier_gate_id"
        ),
        "status": package_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_receipt": (
            package_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_receipt_closeout": (
            package_ready
        ),
        "controlled_dry_run_package_ready": package_ready,
        "dry_run_execution_performed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_package = {
        "dry_run_package_id": package_id,
        "authorization_material_type": "controlled_dry_run_package",
        "source_controlled_apply_preflight_id": future_preflight.get(
            "controlled_apply_preflight_id"
        ),
        "source_final_verifier_gate_id": controlled_preflight.get(
            "source_final_verifier_gate_id"
        ),
        "source_authorization_evidence_execution_closeout_id": (
            controlled_preflight.get(
                "source_authorization_evidence_execution_closeout_id"
            )
        ),
        "source_final_signable_request_package_id": controlled_preflight.get(
            "source_final_signable_request_package_id"
        ),
        "status": package_status,
        "ready_for_future_database_apply_controlled_dry_run_package": (
            package_ready
        ),
        "controlled_dry_run_package_fields": dry_run_package_fields,
        "controlled_dry_run_package_field_count": len(dry_run_package_fields),
        "controlled_dry_run_acceptance_gates": dry_run_acceptance_gates,
        "controlled_dry_run_acceptance_gate_count": len(
            dry_run_acceptance_gates
        ),
        "dry_run_command_shape": command_shape,
        "dry_run_command_shape_hash": command_shape_hash,
        "dry_run_result_parser": dry_run_result_parser,
        "dry_run_result_parser_count": 1,
        "dry_run_result_parser_field_count": len(result_parser_fields),
        "dry_run_execution_receipt_preview": dry_run_execution_receipt_preview,
        "dry_run_execution_receipt_preview_count": 1,
        "dry_run_execution_receipt_field_count": len(receipt_fields),
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "target_file": target_file,
        "expected_sha256": expected_sha256,
        "actual_sha256": actual_sha256,
        "hash_matches": controlled_preflight.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "dry_run_only": True,
        "check_mode_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_package_contract = {
        "mode": "controlled_dry_run_package_and_receipt_preview_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-package"
        ),
        "source_final_preflight_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-apply-final-preflight"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_execution_receipt": (
            package_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_POLICY,
        "result": package_status,
        "success": bool(final_preflight.get("success")),
        "generated_at": final_preflight.get("generated_at"),
        "source_policy": final_preflight.get("policy"),
        "stats": final_preflight.get("stats") or {},
        "summary": {
            "controlled_dry_run_package_ready_count": 1 if package_ready else 0,
            "controlled_dry_run_package_check_count": len(checks),
            "controlled_dry_run_package_pass_count": passed_count,
            "controlled_dry_run_package_waiting_count": len(waiting_checks),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "authorization_verifier_receipt_closeout_ready_count": summary.get(
                "authorization_verifier_receipt_closeout_ready_count", 0
            ),
            "verifier_receipt_closeout_check_count": summary.get(
                "verifier_receipt_closeout_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_package_count": 1,
            "controlled_dry_run_package_field_count": len(dry_run_package_fields),
            "controlled_dry_run_acceptance_gate_count": len(
                dry_run_acceptance_gates
            ),
            "dry_run_execution_receipt_preview_count": 1,
            "dry_run_execution_receipt_field_count": len(receipt_fields),
            "dry_run_result_parser_count": 1,
            "dry_run_result_parser_field_count": len(result_parser_fields),
            "controlled_apply_final_preflight_count": summary.get(
                "controlled_apply_final_preflight_count", 0
            ),
            "controlled_apply_final_preflight_field_count": summary.get(
                "controlled_apply_final_preflight_field_count", 0
            ),
            "controlled_apply_final_preflight_acceptance_gate_count": summary.get(
                "controlled_apply_final_preflight_acceptance_gate_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "rollback_binding_field_count": summary.get(
                "rollback_binding_field_count", 0
            ),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_binding_field_count": summary.get(
                "post_apply_verifier_binding_field_count", 0
            ),
            "authorization_evidence_execution_closeout_field_count": summary.get(
                "authorization_evidence_execution_closeout_field_count", 0
            ),
            "authorization_evidence_execution_closeout_acceptance_gate_count": (
                summary.get(
                    "authorization_evidence_execution_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_execution_receipt": (
            future_database_apply_controlled_dry_run_execution_receipt
        ),
        "controlled_dry_run_package": controlled_dry_run_package,
        "controlled_dry_run_package_contract": controlled_dry_run_package_contract,
        "controlled_dry_run_package_checks": checks,
        "source_controlled_apply_final_preflight_summary": summary,
        "source_controlled_apply_final_preflight_contract": final_preflight_contract,
        "source_controlled_apply_final_preflight": controlled_preflight,
        "source_database_apply_controlled_apply_final_preflight": future_preflight,
        "safety": {
            "read_only_db_apply_controlled_dry_run_package": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this package to build a future controlled dry-run execution receipt closeout.",
            "Keep the dry-run command shape non-executable until a dedicated execution receipt lane is explicit.",
            "This package still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the dry-run receipt preview and parser without execution."""
    package_result = build_pchome_auto_policy_db_apply_controlled_dry_run_package(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    future_receipt = (
        package_result.get("future_database_apply_controlled_dry_run_execution_receipt")
        or {}
    )
    package = package_result.get("controlled_dry_run_package") or {}
    package_contract = package_result.get("controlled_dry_run_package_contract") or {}
    summary = package_result.get("summary") or {}
    safety = package_result.get("safety") or {}
    receipt_preview = package.get("dry_run_execution_receipt_preview") or {}
    command_shape = package.get("dry_run_command_shape") or {}
    result_parser = package.get("dry_run_result_parser") or {}
    rollback_binding = package.get("rollback_binding") or {}
    verifier_binding = package.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_receipt_closeout_id(package_result)
    receipt_closeout_fields = [
        "receipt_closeout_id",
        "source_dry_run_package_id",
        "source_controlled_apply_preflight_id",
        "source_dry_run_execution_receipt_id",
        "dry_run_command_shape_hash",
        "dry_run_result_parser_id",
        "receipt_validation_status",
        "target_migration_file",
        "target_migration_sha256",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "abort_conditions",
    ]
    receipt_closeout_acceptance_gates = [
        "controlled_dry_run_package_ready",
        "source_chain_ids_match",
        "result_parser_schema_complete",
        "receipt_preview_schema_match",
        "command_shape_hash_match",
        "receipt_preview_not_executed",
        "target_migration_hash_locked",
        "no_secret_signature_or_database_apply",
        "no_endpoint_sql_or_db_write",
        "exception_only_failure_routing",
    ]
    receipt_validation_fields = [
        "receipt_id",
        "source_dry_run_package_id",
        "dry_run_status",
        "dry_run_command_shape_hash",
        "execution_performed",
        "stdout_included",
        "stderr_included",
        "database_apply_authorized",
    ]
    target_hash_locked = (
        package.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(package.get("expected_sha256"))
        and bool(package.get("actual_sha256"))
        and package.get("expected_sha256") == package.get("actual_sha256")
        and package.get("hash_matches") is True
        and package.get("target_migration_hash_locked") is True
    )
    parser_schema_complete = (
        bool(result_parser.get("parser_id"))
        and result_parser.get("source_dry_run_package_id")
        == package.get("dry_run_package_id")
        and result_parser.get("expected_receipt_status")
        == "preview_only_not_executed"
        and result_parser.get("required_command_shape_hash")
        == package.get("dry_run_command_shape_hash")
        and result_parser.get("execution_required") is False
        and result_parser.get("stdout_allowed") is False
        and result_parser.get("stderr_allowed") is False
        and result_parser.get("database_apply_authorized") is False
        and int(result_parser.get("parser_field_count") or 0) == 10
    )
    required_receipt_fields = result_parser.get("required_receipt_fields") or []
    receipt_schema_matches_parser = (
        parser_schema_complete
        and receipt_preview.get("source_dry_run_package_id")
        == package.get("dry_run_package_id")
        and receipt_preview.get("dry_run_status")
        == result_parser.get("expected_receipt_status")
        and receipt_preview.get("dry_run_command_shape_hash")
        == result_parser.get("required_command_shape_hash")
        and int(receipt_preview.get("receipt_field_count") or 0) == 8
        and all(field in receipt_preview for field in required_receipt_fields)
    )
    command_hash_matches_receipt = (
        bool(package.get("dry_run_command_shape_hash"))
        and package.get("dry_run_command_shape_hash")
        == receipt_preview.get("dry_run_command_shape_hash")
        == result_parser.get("required_command_shape_hash")
    )
    command_shape_preview_only = (
        command_shape.get("dry_run_only") is True
        and command_shape.get("check_mode_only") is True
        and command_shape.get("execution_allowed") is False
        and command_shape.get("shell_command_included") is False
        and command_shape.get("sql_included") is False
        and command_shape.get("endpoint_execution_included") is False
        and command_shape.get("database_write_included") is False
    )
    receipt_preview_only = (
        receipt_preview.get("execution_performed") is False
        and receipt_preview.get("stdout_included") is False
        and receipt_preview.get("stderr_included") is False
        and receipt_preview.get("database_apply_authorized") is False
        and receipt_preview.get("executes_shell") is False
        and receipt_preview.get("executes_endpoint") is False
        and receipt_preview.get("executes_sql") is False
        and receipt_preview.get("writes_database") is False
        and receipt_preview.get("reads_secret") is False
    )
    receipt_validation_report = {
        "receipt_id": receipt_preview.get("receipt_id"),
        "source_dry_run_package_id": package.get("dry_run_package_id"),
        "dry_run_status": receipt_preview.get("dry_run_status"),
        "dry_run_command_shape_hash": receipt_preview.get(
            "dry_run_command_shape_hash"
        ),
        "execution_performed": False,
        "stdout_included": False,
        "stderr_included": False,
        "database_apply_authorized": False,
        "receipt_validation_status": (
            "preview_validated_not_executed"
            if receipt_schema_matches_parser and command_hash_matches_receipt
            else "waiting_for_receipt_parser_schema_match"
        ),
        "receipt_validation_field_count": len(receipt_validation_fields),
        "receipt_validation_fields": receipt_validation_fields,
        "executes_shell": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret": False,
    }
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and package.get("accepts_plaintext_secret") is False
        and package.get("reads_secret_in_preview") is False
        and package.get("signature_material_included") is False
        and package.get("secret_material_included") is False
        and package.get("signs_database_apply_authorization") is False
        and package.get("executes_authorization_evidence") is False
        and package.get("executes_database_apply") is False
        and package.get("executes_endpoint_in_preview") is False
        and package.get("executes_sql_in_preview") is False
        and package.get("writes_database_in_preview") is False
        and command_shape_preview_only
        and receipt_preview_only
    )
    checks = [
        _controlled_dry_run_receipt_closeout_check(
            "controlled_dry_run_package_ready",
            package_result.get("result") == "DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_READY"
            and future_receipt.get(
                "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
            )
            is True
            and future_receipt.get(
                "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
            )
            is True
            and package.get("ready_for_future_database_apply_controlled_dry_run_package")
            is True,
            {
                "result": package_result.get("result"),
                "ready_for_future_database_apply_controlled_dry_run_execution_receipt": (
                    future_receipt.get(
                        "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_receipt_closeout": (
                    future_receipt.get(
                        "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
                    )
                ),
            },
            "wait_for_controlled_dry_run_package",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "source_chain_ids_present",
            bool(package.get("dry_run_package_id"))
            and bool(future_receipt.get("dry_run_execution_receipt_id"))
            and bool(package.get("source_controlled_apply_preflight_id"))
            and bool(package.get("source_final_verifier_gate_id"))
            and bool(package.get("source_authorization_evidence_execution_closeout_id")),
            {
                "dry_run_package_id": package.get("dry_run_package_id"),
                "dry_run_execution_receipt_id": future_receipt.get(
                    "dry_run_execution_receipt_id"
                ),
                "source_controlled_apply_preflight_id": package.get(
                    "source_controlled_apply_preflight_id"
                ),
            },
            "wait_for_controlled_dry_run_source_chain_ids",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "controlled_dry_run_receipt_closeout_contract_complete",
            len(receipt_closeout_fields) == 12
            and len(receipt_closeout_acceptance_gates) == 10
            and len(receipt_validation_fields) == 8
            and "dry_run_result_parser_id" in receipt_closeout_fields
            and "receipt_preview_schema_match" in receipt_closeout_acceptance_gates,
            {
                "receipt_closeout_field_count": len(receipt_closeout_fields),
                "receipt_closeout_acceptance_gate_count": len(
                    receipt_closeout_acceptance_gates
                ),
                "receipt_validation_field_count": len(receipt_validation_fields),
            },
            "wait_for_receipt_closeout_contract",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "dry_run_result_parser_schema_complete",
            parser_schema_complete,
            {
                "parser_id": result_parser.get("parser_id"),
                "parser_field_count": result_parser.get("parser_field_count"),
                "execution_required": result_parser.get("execution_required"),
                "database_apply_authorized": result_parser.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_dry_run_result_parser_schema",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "receipt_preview_schema_matches_parser",
            receipt_schema_matches_parser,
            {
                "receipt_id": receipt_preview.get("receipt_id"),
                "dry_run_status": receipt_preview.get("dry_run_status"),
                "required_receipt_field_count": len(required_receipt_fields),
                "receipt_field_count": receipt_preview.get("receipt_field_count"),
            },
            "wait_for_receipt_preview_parser_match",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "command_shape_hash_matches_receipt",
            command_hash_matches_receipt,
            {
                "dry_run_command_shape_hash_present": bool(
                    package.get("dry_run_command_shape_hash")
                ),
                "receipt_hash_matches": (
                    package.get("dry_run_command_shape_hash")
                    == receipt_preview.get("dry_run_command_shape_hash")
                ),
            },
            "abort_on_dry_run_command_shape_hash_mismatch",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "receipt_preview_only_not_executed",
            receipt_preview_only and command_shape_preview_only,
            {
                "execution_performed": receipt_preview.get("execution_performed"),
                "stdout_included": receipt_preview.get("stdout_included"),
                "stderr_included": receipt_preview.get("stderr_included"),
                "execution_allowed": command_shape.get("execution_allowed"),
            },
            "abort_if_receipt_or_command_shape_indicates_execution",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            bool(rollback_binding.get("rollback_binding_id"))
            and rollback_binding.get("rollback_execution_authorized") is False
            and rollback_binding.get("rollback_executes_sql") is False
            and rollback_binding.get("rollback_writes_database") is False
            and bool(verifier_binding.get("post_apply_verifier_binding_id"))
            and verifier_binding.get("verifier_must_run_after_apply") is True
            and verifier_binding.get("verifier_execution_authorized_in_preview")
            is False
            and verifier_binding.get("database_apply_authorized") is False,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": package.get("target_file"),
                "expected_sha256_present": bool(package.get("expected_sha256")),
                "actual_sha256_present": bool(package.get("actual_sha256")),
                "hash_matches": package.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "package_contract_blocks_database_apply",
            package_contract.get(
                "permits_future_database_apply_controlled_dry_run_execution_receipt"
            )
            is True
            and package_contract.get("executes_database_apply") is False
            and package_contract.get("database_apply_authorized") is False
            and package_contract.get("ready_for_database_apply_now") is False
            and package_contract.get("signs_database_apply_authorization") is False
            and package_contract.get("writes_database") is False,
            {
                "permits_future_database_apply_controlled_dry_run_execution_receipt": (
                    package_contract.get(
                        "permits_future_database_apply_controlled_dry_run_execution_receipt"
                    )
                ),
                "database_apply_authorized": package_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": package_contract.get("writes_database"),
            },
            "abort_if_dry_run_package_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "command_shape_preview_only": command_shape_preview_only,
                "receipt_preview_only": receipt_preview_only,
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_receipt_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0
            and future_receipt.get("manual_review_mode") == "exception_only",
            {
                LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(
                    LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0
                ),
                "manual_review_mode": future_receipt.get("manual_review_mode"),
            },
            "route_failed_receipt_closeout_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE"
    )
    future_database_apply_controlled_dry_run_result_parser_verification = {
        "receipt_closeout_id": closeout_id,
        "source_dry_run_package_id": package.get("dry_run_package_id"),
        "source_dry_run_execution_receipt_id": future_receipt.get(
            "dry_run_execution_receipt_id"
        ),
        "dry_run_result_parser_id": result_parser.get("parser_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_result_parser_verification": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_runner_readiness": (
            closeout_ready
        ),
        "controlled_dry_run_receipt_closeout_ready": closeout_ready,
        "receipt_validation_status": receipt_validation_report.get(
            "receipt_validation_status"
        ),
        "dry_run_execution_performed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_receipt_closeout = {
        "receipt_closeout_id": closeout_id,
        "authorization_material_type": "controlled_dry_run_receipt_closeout",
        "source_dry_run_package_id": package.get("dry_run_package_id"),
        "source_controlled_apply_preflight_id": package.get(
            "source_controlled_apply_preflight_id"
        ),
        "source_dry_run_execution_receipt_id": future_receipt.get(
            "dry_run_execution_receipt_id"
        ),
        "dry_run_result_parser_id": result_parser.get("parser_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_receipt_closeout": (
            closeout_ready
        ),
        "controlled_dry_run_receipt_closeout_fields": receipt_closeout_fields,
        "controlled_dry_run_receipt_closeout_field_count": len(
            receipt_closeout_fields
        ),
        "controlled_dry_run_receipt_closeout_acceptance_gates": (
            receipt_closeout_acceptance_gates
        ),
        "controlled_dry_run_receipt_closeout_acceptance_gate_count": len(
            receipt_closeout_acceptance_gates
        ),
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "dry_run_result_parser_field_count": int(
            result_parser.get("parser_field_count") or 0
        ),
        "receipt_validation_report": receipt_validation_report,
        "receipt_validation_report_count": 1,
        "receipt_validation_field_count": len(receipt_validation_fields),
        "dry_run_command_shape_hash": package.get("dry_run_command_shape_hash"),
        "target_file": package.get("target_file"),
        "expected_sha256": package.get("expected_sha256"),
        "actual_sha256": package.get("actual_sha256"),
        "hash_matches": package.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "dry_run_only": True,
        "check_mode_only": True,
        "receipt_preview_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_receipt_closeout_contract = {
        "mode": "controlled_dry_run_receipt_closeout_and_result_parser_verification_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-receipt-closeout"
        ),
        "source_dry_run_package_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-package"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_runner_readiness": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(package_result.get("success")),
        "generated_at": package_result.get("generated_at"),
        "source_policy": package_result.get("policy"),
        "stats": package_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_receipt_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": len(checks),
            "controlled_dry_run_receipt_closeout_pass_count": passed_count,
            "controlled_dry_run_receipt_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "authorization_verifier_receipt_closeout_ready_count": summary.get(
                "authorization_verifier_receipt_closeout_ready_count", 0
            ),
            "verifier_receipt_closeout_check_count": summary.get(
                "verifier_receipt_closeout_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_receipt_closeout_count": 1,
            "controlled_dry_run_receipt_closeout_field_count": len(
                receipt_closeout_fields
            ),
            "controlled_dry_run_receipt_closeout_acceptance_gate_count": len(
                receipt_closeout_acceptance_gates
            ),
            "dry_run_result_parser_count": 1,
            "dry_run_result_parser_field_count": int(
                result_parser.get("parser_field_count") or 0
            ),
            "receipt_validation_report_count": 1,
            "receipt_validation_field_count": len(receipt_validation_fields),
            "dry_run_execution_receipt_preview_count": summary.get(
                "dry_run_execution_receipt_preview_count", 0
            ),
            "dry_run_execution_receipt_field_count": summary.get(
                "dry_run_execution_receipt_field_count", 0
            ),
            "controlled_dry_run_package_count": summary.get(
                "controlled_dry_run_package_count", 0
            ),
            "controlled_dry_run_package_field_count": summary.get(
                "controlled_dry_run_package_field_count", 0
            ),
            "controlled_dry_run_acceptance_gate_count": summary.get(
                "controlled_dry_run_acceptance_gate_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_result_parser_verification": (
            future_database_apply_controlled_dry_run_result_parser_verification
        ),
        "controlled_dry_run_receipt_closeout": controlled_dry_run_receipt_closeout,
        "controlled_dry_run_receipt_closeout_contract": (
            controlled_dry_run_receipt_closeout_contract
        ),
        "controlled_dry_run_receipt_closeout_checks": checks,
        "source_controlled_dry_run_package_summary": summary,
        "source_controlled_dry_run_package_contract": package_contract,
        "source_controlled_dry_run_package": package,
        "source_database_apply_controlled_dry_run_execution_receipt": (
            future_receipt
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_receipt_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run runner readiness package.",
            "Keep result parsing bound to receipt preview fields and command-shape hash before any execution lane.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_runner_readiness(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Bind a future dry-run runner execution plan without authorizing it."""
    receipt_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_verification = (
        receipt_closeout_result.get(
            "future_database_apply_controlled_dry_run_result_parser_verification"
        )
        or {}
    )
    receipt_closeout = (
        receipt_closeout_result.get("controlled_dry_run_receipt_closeout") or {}
    )
    closeout_contract = (
        receipt_closeout_result.get("controlled_dry_run_receipt_closeout_contract")
        or {}
    )
    summary = receipt_closeout_result.get("summary") or {}
    safety = receipt_closeout_result.get("safety") or {}
    result_parser = receipt_closeout.get("dry_run_result_parser") or {}
    validation = receipt_closeout.get("receipt_validation_report") or {}
    rollback_binding = receipt_closeout.get("rollback_binding") or {}
    verifier_binding = receipt_closeout.get("post_apply_verifier_binding") or {}
    runner_readiness_id = _db_apply_controlled_dry_run_runner_readiness_id(
        receipt_closeout_result
    )
    execution_plan_binding_id = f"{runner_readiness_id}-execution-plan-binding"
    runner_readiness_fields = [
        "runner_readiness_id",
        "source_receipt_closeout_id",
        "source_dry_run_package_id",
        "source_controlled_apply_preflight_id",
        "source_dry_run_execution_receipt_id",
        "dry_run_result_parser_id",
        "receipt_validation_status",
        "dry_run_command_shape_hash",
        "execution_plan_binding_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
    ]
    runner_readiness_acceptance_gates = [
        "receipt_closeout_ready",
        "source_chain_ids_match",
        "result_parser_verified",
        "receipt_validation_report_ready",
        "command_shape_hash_bound",
        "execution_plan_binding_preview_only",
        "runner_execution_gate_closed",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "closeout_contract_blocks_database_apply",
    ]
    execution_plan_binding_fields = [
        "execution_plan_binding_id",
        "source_receipt_closeout_id",
        "source_dry_run_package_id",
        "dry_run_command_shape_hash",
        "runner_mode",
        "plan_status",
        "dry_run_only",
        "check_mode_only",
        "shell_execution_included",
        "endpoint_execution_included",
        "sql_execution_included",
        "database_write_included",
    ]
    target_hash_locked = (
        receipt_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(receipt_closeout.get("expected_sha256"))
        and bool(receipt_closeout.get("actual_sha256"))
        and receipt_closeout.get("expected_sha256")
        == receipt_closeout.get("actual_sha256")
        and receipt_closeout.get("hash_matches") is True
        and receipt_closeout.get("target_migration_hash_locked") is True
    )
    result_parser_verified = (
        bool(result_parser.get("parser_id"))
        and result_parser.get("parser_id")
        == receipt_closeout.get("dry_run_result_parser_id")
        and result_parser.get("expected_receipt_status")
        == "preview_only_not_executed"
        and result_parser.get("required_command_shape_hash")
        == receipt_closeout.get("dry_run_command_shape_hash")
        and result_parser.get("execution_required") is False
        and result_parser.get("stdout_allowed") is False
        and result_parser.get("stderr_allowed") is False
        and result_parser.get("database_apply_authorized") is False
        and int(result_parser.get("parser_field_count") or 0) == 10
    )
    receipt_validation_ready = (
        validation.get("receipt_validation_status")
        == "preview_validated_not_executed"
        and validation.get("dry_run_command_shape_hash")
        == receipt_closeout.get("dry_run_command_shape_hash")
        and validation.get("execution_performed") is False
        and validation.get("stdout_included") is False
        and validation.get("stderr_included") is False
        and validation.get("database_apply_authorized") is False
        and validation.get("executes_shell") is False
        and validation.get("executes_endpoint") is False
        and validation.get("executes_sql") is False
        and validation.get("writes_database") is False
        and validation.get("reads_secret") is False
        and int(validation.get("receipt_validation_field_count") or 0) == 8
    )
    command_shape_hash_bound = (
        bool(receipt_closeout.get("dry_run_command_shape_hash"))
        and receipt_closeout.get("dry_run_command_shape_hash")
        == validation.get("dry_run_command_shape_hash")
        == result_parser.get("required_command_shape_hash")
    )
    execution_plan_binding = {
        "execution_plan_binding_id": execution_plan_binding_id,
        "source_runner_readiness_id": runner_readiness_id,
        "source_receipt_closeout_id": receipt_closeout.get("receipt_closeout_id"),
        "source_dry_run_package_id": receipt_closeout.get("source_dry_run_package_id"),
        "dry_run_command_shape_hash": receipt_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "runner_mode": "future_controlled_dry_run_runner_readiness_only",
        "plan_status": "plan_binding_preview_not_executable",
        "dry_run_only": True,
        "check_mode_only": True,
        "execution_authorized": False,
        "dry_run_execution_authorized": False,
        "runner_execution_authorized": False,
        "shell_execution_included": False,
        "endpoint_execution_included": False,
        "sql_execution_included": False,
        "database_write_included": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "execution_plan_binding_field_count": len(execution_plan_binding_fields),
        "execution_plan_binding_fields": execution_plan_binding_fields,
    }
    execution_plan_preview_only = (
        execution_plan_binding.get("dry_run_only") is True
        and execution_plan_binding.get("check_mode_only") is True
        and execution_plan_binding.get("execution_authorized") is False
        and execution_plan_binding.get("dry_run_execution_authorized") is False
        and execution_plan_binding.get("runner_execution_authorized") is False
        and execution_plan_binding.get("shell_execution_included") is False
        and execution_plan_binding.get("endpoint_execution_included") is False
        and execution_plan_binding.get("sql_execution_included") is False
        and execution_plan_binding.get("database_write_included") is False
        and execution_plan_binding.get("stdout_capture_allowed") is False
        and execution_plan_binding.get("stderr_capture_allowed") is False
        and execution_plan_binding.get("database_apply_authorized") is False
    )
    runner_execution_gate_closed = (
        future_verification.get(
            "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
        )
        is True
        and future_verification.get(
            "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
        )
        is True
        and future_verification.get("dry_run_execution_performed") is False
        and future_verification.get("database_apply_authorized") is False
        and future_verification.get("executes_database_apply") is False
        and future_verification.get("executes_endpoint") is False
        and future_verification.get("executes_sql") is False
        and future_verification.get("writes_database") is False
        and execution_plan_preview_only
    )
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and receipt_closeout.get("accepts_plaintext_secret") is False
        and receipt_closeout.get("reads_secret_in_preview") is False
        and receipt_closeout.get("signature_material_included") is False
        and receipt_closeout.get("secret_material_included") is False
        and receipt_closeout.get("signs_database_apply_authorization") is False
        and receipt_closeout.get("executes_authorization_evidence") is False
        and receipt_closeout.get("executes_database_apply") is False
        and receipt_closeout.get("executes_endpoint_in_preview") is False
        and receipt_closeout.get("executes_sql_in_preview") is False
        and receipt_closeout.get("writes_database_in_preview") is False
        and receipt_validation_ready
        and execution_plan_preview_only
    )
    checks = [
        _controlled_dry_run_runner_readiness_check(
            "receipt_closeout_ready",
            receipt_closeout_result.get("result")
            == "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_READY"
            and future_verification.get(
                "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
            )
            is True
            and future_verification.get(
                "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True
            and receipt_closeout.get(
                "ready_for_future_database_apply_controlled_dry_run_receipt_closeout"
            )
            is True,
            {
                "result": receipt_closeout_result.get("result"),
                "ready_for_future_database_apply_controlled_dry_run_result_parser_verification": (
                    future_verification.get(
                        "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_runner_readiness": (
                    future_verification.get(
                        "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
                    )
                ),
            },
            "wait_for_controlled_dry_run_receipt_closeout",
        ),
        _controlled_dry_run_runner_readiness_check(
            "source_chain_ids_present",
            bool(receipt_closeout.get("receipt_closeout_id"))
            and bool(receipt_closeout.get("source_dry_run_package_id"))
            and bool(receipt_closeout.get("source_controlled_apply_preflight_id"))
            and bool(receipt_closeout.get("source_dry_run_execution_receipt_id"))
            and bool(receipt_closeout.get("dry_run_result_parser_id")),
            {
                "receipt_closeout_id": receipt_closeout.get("receipt_closeout_id"),
                "source_dry_run_package_id": receipt_closeout.get(
                    "source_dry_run_package_id"
                ),
                "dry_run_result_parser_id": receipt_closeout.get(
                    "dry_run_result_parser_id"
                ),
            },
            "wait_for_runner_readiness_source_chain_ids",
        ),
        _controlled_dry_run_runner_readiness_check(
            "controlled_dry_run_runner_readiness_contract_complete",
            len(runner_readiness_fields) == 12
            and len(runner_readiness_acceptance_gates) == 10
            and len(execution_plan_binding_fields) == 12
            and "execution_plan_binding_id" in runner_readiness_fields
            and "execution_plan_binding_preview_only"
            in runner_readiness_acceptance_gates,
            {
                "runner_readiness_field_count": len(runner_readiness_fields),
                "runner_readiness_acceptance_gate_count": len(
                    runner_readiness_acceptance_gates
                ),
                "execution_plan_binding_field_count": len(
                    execution_plan_binding_fields
                ),
            },
            "wait_for_runner_readiness_contract",
        ),
        _controlled_dry_run_runner_readiness_check(
            "dry_run_result_parser_verified",
            result_parser_verified,
            {
                "parser_id": result_parser.get("parser_id"),
                "parser_field_count": result_parser.get("parser_field_count"),
                "execution_required": result_parser.get("execution_required"),
                "database_apply_authorized": result_parser.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_dry_run_result_parser_verification",
        ),
        _controlled_dry_run_runner_readiness_check(
            "receipt_validation_report_ready",
            receipt_validation_ready,
            {
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
                "receipt_validation_field_count": validation.get(
                    "receipt_validation_field_count"
                ),
                "execution_performed": validation.get("execution_performed"),
            },
            "wait_for_receipt_validation_report",
        ),
        _controlled_dry_run_runner_readiness_check(
            "command_shape_hash_bound",
            command_shape_hash_bound,
            {
                "dry_run_command_shape_hash_present": bool(
                    receipt_closeout.get("dry_run_command_shape_hash")
                ),
                "parser_hash_matches": (
                    receipt_closeout.get("dry_run_command_shape_hash")
                    == result_parser.get("required_command_shape_hash")
                ),
                "validation_hash_matches": (
                    receipt_closeout.get("dry_run_command_shape_hash")
                    == validation.get("dry_run_command_shape_hash")
                ),
            },
            "abort_on_runner_command_shape_hash_mismatch",
        ),
        _controlled_dry_run_runner_readiness_check(
            "execution_plan_binding_preview_only",
            execution_plan_preview_only,
            {
                "execution_authorized": execution_plan_binding.get(
                    "execution_authorized"
                ),
                "runner_execution_authorized": execution_plan_binding.get(
                    "runner_execution_authorized"
                ),
                "database_write_included": execution_plan_binding.get(
                    "database_write_included"
                ),
            },
            "abort_if_execution_plan_binding_is_executable",
        ),
        _controlled_dry_run_runner_readiness_check(
            "runner_execution_gate_closed",
            runner_execution_gate_closed,
            {
                "dry_run_execution_performed": future_verification.get(
                    "dry_run_execution_performed"
                ),
                "database_apply_authorized": future_verification.get(
                    "database_apply_authorized"
                ),
                "writes_database": future_verification.get("writes_database"),
            },
            "abort_if_runner_execution_gate_opens",
        ),
        _controlled_dry_run_runner_readiness_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": receipt_closeout.get("target_file"),
                "expected_sha256_present": bool(receipt_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(receipt_closeout.get("actual_sha256")),
                "hash_matches": receipt_closeout.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_runner_readiness_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            bool(rollback_binding.get("rollback_binding_id"))
            and rollback_binding.get("rollback_execution_authorized") is False
            and rollback_binding.get("rollback_executes_sql") is False
            and rollback_binding.get("rollback_writes_database") is False
            and bool(verifier_binding.get("post_apply_verifier_binding_id"))
            and verifier_binding.get("verifier_must_run_after_apply") is True
            and verifier_binding.get("verifier_execution_authorized_in_preview")
            is False
            and verifier_binding.get("database_apply_authorized") is False,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_runner_readiness_check(
            "closeout_contract_blocks_database_apply",
            closeout_contract.get(
                "permits_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True
            and closeout_contract.get("executes_database_apply") is False
            and closeout_contract.get("database_apply_authorized") is False
            and closeout_contract.get("ready_for_database_apply_now") is False
            and closeout_contract.get("signs_database_apply_authorization") is False
            and closeout_contract.get("writes_database") is False,
            {
                "permits_future_database_apply_controlled_dry_run_runner_readiness": (
                    closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_runner_readiness"
                    )
                ),
                "database_apply_authorized": closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": closeout_contract.get("writes_database"),
            },
            "abort_if_receipt_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_runner_readiness_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "execution_plan_preview_only": execution_plan_preview_only,
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    runner_ready = not waiting_checks
    runner_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_READY"
        if runner_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_execution_plan_binding = {
        "runner_readiness_id": runner_readiness_id,
        "execution_plan_binding_id": execution_plan_binding_id,
        "source_receipt_closeout_id": receipt_closeout.get("receipt_closeout_id"),
        "source_dry_run_package_id": receipt_closeout.get("source_dry_run_package_id"),
        "source_dry_run_execution_receipt_id": receipt_closeout.get(
            "source_dry_run_execution_receipt_id"
        ),
        "status": runner_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding": (
            runner_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout": (
            runner_ready
        ),
        "controlled_dry_run_runner_readiness_ready": runner_ready,
        "execution_plan_bound": runner_ready,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_runner_readiness = {
        "runner_readiness_id": runner_readiness_id,
        "authorization_material_type": "controlled_dry_run_runner_readiness",
        "source_receipt_closeout_id": receipt_closeout.get("receipt_closeout_id"),
        "source_dry_run_package_id": receipt_closeout.get("source_dry_run_package_id"),
        "source_controlled_apply_preflight_id": receipt_closeout.get(
            "source_controlled_apply_preflight_id"
        ),
        "source_dry_run_execution_receipt_id": receipt_closeout.get(
            "source_dry_run_execution_receipt_id"
        ),
        "dry_run_result_parser_id": receipt_closeout.get(
            "dry_run_result_parser_id"
        ),
        "status": runner_status,
        "ready_for_future_database_apply_controlled_dry_run_runner_readiness": (
            runner_ready
        ),
        "controlled_dry_run_runner_readiness_fields": runner_readiness_fields,
        "controlled_dry_run_runner_readiness_field_count": len(
            runner_readiness_fields
        ),
        "controlled_dry_run_runner_readiness_acceptance_gates": (
            runner_readiness_acceptance_gates
        ),
        "controlled_dry_run_runner_readiness_acceptance_gate_count": len(
            runner_readiness_acceptance_gates
        ),
        "execution_plan_binding": execution_plan_binding,
        "execution_plan_binding_count": 1,
        "execution_plan_binding_field_count": len(execution_plan_binding_fields),
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "dry_run_command_shape_hash": receipt_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "target_file": receipt_closeout.get("target_file"),
        "expected_sha256": receipt_closeout.get("expected_sha256"),
        "actual_sha256": receipt_closeout.get("actual_sha256"),
        "hash_matches": receipt_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "dry_run_only": True,
        "check_mode_only": True,
        "runner_readiness_only": True,
        "execution_plan_preview_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_runner_readiness_contract = {
        "mode": "controlled_dry_run_runner_readiness_and_execution_plan_binding_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-runner-readiness"
        ),
        "source_receipt_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-receipt-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_execution_plan_binding": (
            runner_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_POLICY,
        "result": runner_status,
        "success": bool(receipt_closeout_result.get("success")),
        "generated_at": receipt_closeout_result.get("generated_at"),
        "source_policy": receipt_closeout_result.get("policy"),
        "stats": receipt_closeout_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_runner_readiness_ready_count": (
                1 if runner_ready else 0
            ),
            "controlled_dry_run_runner_readiness_check_count": len(checks),
            "controlled_dry_run_runner_readiness_pass_count": passed_count,
            "controlled_dry_run_runner_readiness_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_readiness_count": 1,
            "controlled_dry_run_runner_readiness_field_count": len(
                runner_readiness_fields
            ),
            "controlled_dry_run_runner_readiness_acceptance_gate_count": len(
                runner_readiness_acceptance_gates
            ),
            "execution_plan_binding_count": 1,
            "execution_plan_binding_field_count": len(execution_plan_binding_fields),
            "dry_run_result_parser_count": summary.get(
                "dry_run_result_parser_count", 0
            ),
            "dry_run_result_parser_field_count": summary.get(
                "dry_run_result_parser_field_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "controlled_dry_run_receipt_closeout_count": summary.get(
                "controlled_dry_run_receipt_closeout_count", 0
            ),
            "controlled_dry_run_receipt_closeout_field_count": summary.get(
                "controlled_dry_run_receipt_closeout_field_count", 0
            ),
            "controlled_dry_run_receipt_closeout_acceptance_gate_count": summary.get(
                "controlled_dry_run_receipt_closeout_acceptance_gate_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_execution_plan_binding": (
            future_database_apply_controlled_dry_run_execution_plan_binding
        ),
        "controlled_dry_run_runner_readiness": controlled_dry_run_runner_readiness,
        "controlled_dry_run_runner_readiness_contract": (
            controlled_dry_run_runner_readiness_contract
        ),
        "controlled_dry_run_runner_readiness_checks": checks,
        "source_controlled_dry_run_receipt_closeout_summary": summary,
        "source_controlled_dry_run_receipt_closeout_contract": closeout_contract,
        "source_controlled_dry_run_receipt_closeout": receipt_closeout,
        "source_database_apply_controlled_dry_run_result_parser_verification": (
            future_verification
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_runner_readiness": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this readiness package to build a future controlled dry-run execution plan closeout.",
            "Keep runner execution authorization closed until a dedicated execution receipt lane is explicit.",
            "This readiness package still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out a future dry-run execution plan as a non-executable artifact."""
    runner_readiness_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_readiness(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_plan = (
        runner_readiness_result.get(
            "future_database_apply_controlled_dry_run_execution_plan_binding"
        )
        or {}
    )
    runner = (
        runner_readiness_result.get("controlled_dry_run_runner_readiness") or {}
    )
    runner_contract = (
        runner_readiness_result.get("controlled_dry_run_runner_readiness_contract")
        or {}
    )
    summary = runner_readiness_result.get("summary") or {}
    safety = runner_readiness_result.get("safety") or {}
    execution_plan_binding = runner.get("execution_plan_binding") or {}
    validation = runner.get("receipt_validation_report") or {}
    result_parser = runner.get("dry_run_result_parser") or {}
    rollback_binding = runner.get("rollback_binding") or {}
    verifier_binding = runner.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_execution_plan_closeout_id(
        runner_readiness_result
    )
    artifact_id = f"{closeout_id}-non-executable-command-artifact"
    execution_plan_closeout_fields = [
        "execution_plan_closeout_id",
        "source_runner_readiness_id",
        "source_execution_plan_binding_id",
        "source_receipt_closeout_id",
        "source_dry_run_package_id",
        "dry_run_command_shape_hash",
        "non_executable_command_artifact_id",
        "non_executable_command_artifact_sha256",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "abort_conditions",
    ]
    execution_plan_closeout_acceptance_gates = [
        "runner_readiness_ready",
        "source_chain_ids_match",
        "execution_plan_binding_preview_only",
        "non_executable_command_artifact_bound",
        "command_artifact_hash_locked",
        "runner_execution_gate_closed",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "runner_contract_blocks_database_apply",
        "no_secret_signature_or_database_apply",
    ]
    non_executable_command_artifact_fields = [
        "artifact_id",
        "source_execution_plan_binding_id",
        "dry_run_command_shape_hash",
        "artifact_type",
        "shell_command_included",
        "endpoint_execution_included",
        "sql_execution_included",
        "database_write_included",
        "execution_authorized",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_runner_readiness_not_ready",
        "abort_if_execution_plan_becomes_executable",
        "abort_if_command_artifact_contains_shell_command_or_argv",
        "abort_if_command_artifact_hash_missing",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_runner_contract_authorizes_database_apply",
        "abort_if_any_endpoint_sql_database_write_or_signature_is_requested",
    ]
    non_executable_command_artifact = {
        "artifact_id": artifact_id,
        "source_runner_readiness_id": runner.get("runner_readiness_id"),
        "source_execution_plan_binding_id": execution_plan_binding.get(
            "execution_plan_binding_id"
        ),
        "source_receipt_closeout_id": runner.get("source_receipt_closeout_id"),
        "source_dry_run_package_id": runner.get("source_dry_run_package_id"),
        "dry_run_command_shape_hash": runner.get("dry_run_command_shape_hash"),
        "artifact_type": "non_executable_command_artifact_reference",
        "command_text_included": False,
        "argv_included": False,
        "shell_command_included": False,
        "endpoint_execution_included": False,
        "sql_execution_included": False,
        "database_write_included": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "execution_authorized": False,
        "dry_run_execution_authorized": False,
        "runner_execution_authorized": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "non_executable_command_artifact_field_count": len(
            non_executable_command_artifact_fields
        ),
        "non_executable_command_artifact_fields": (
            non_executable_command_artifact_fields
        ),
    }
    artifact_hash_payload = {
        key: value
        for key, value in non_executable_command_artifact.items()
        if key != "non_executable_command_artifact_sha256"
    }
    artifact_sha256 = hashlib.sha256(
        json.dumps(artifact_hash_payload, sort_keys=True).encode("utf-8")
    ).hexdigest()
    non_executable_command_artifact[
        "non_executable_command_artifact_sha256"
    ] = artifact_sha256
    execution_plan_preview_only = (
        execution_plan_binding.get("dry_run_only") is True
        and execution_plan_binding.get("check_mode_only") is True
        and execution_plan_binding.get("execution_authorized") is False
        and execution_plan_binding.get("dry_run_execution_authorized") is False
        and execution_plan_binding.get("runner_execution_authorized") is False
        and execution_plan_binding.get("shell_execution_included") is False
        and execution_plan_binding.get("endpoint_execution_included") is False
        and execution_plan_binding.get("sql_execution_included") is False
        and execution_plan_binding.get("database_write_included") is False
        and execution_plan_binding.get("stdout_capture_allowed") is False
        and execution_plan_binding.get("stderr_capture_allowed") is False
        and execution_plan_binding.get("database_apply_authorized") is False
        and execution_plan_binding.get("ready_for_database_apply_now") is False
    )
    non_executable_command_artifact_bound = (
        non_executable_command_artifact.get("artifact_type")
        == "non_executable_command_artifact_reference"
        and bool(non_executable_command_artifact.get("artifact_id"))
        and bool(
            non_executable_command_artifact.get("source_execution_plan_binding_id")
        )
        and bool(non_executable_command_artifact.get("dry_run_command_shape_hash"))
        and non_executable_command_artifact.get("command_text_included") is False
        and non_executable_command_artifact.get("argv_included") is False
        and non_executable_command_artifact.get("shell_command_included") is False
        and non_executable_command_artifact.get("endpoint_execution_included")
        is False
        and non_executable_command_artifact.get("sql_execution_included") is False
        and non_executable_command_artifact.get("database_write_included") is False
        and non_executable_command_artifact.get("execution_authorized") is False
        and non_executable_command_artifact.get("database_apply_authorized")
        is False
        and int(
            non_executable_command_artifact.get(
                "non_executable_command_artifact_field_count"
            )
            or 0
        )
        == 10
    )
    command_artifact_hash_locked = (
        bool(artifact_sha256)
        and len(artifact_sha256) == 64
        and non_executable_command_artifact.get(
            "non_executable_command_artifact_sha256"
        )
        == artifact_sha256
    )
    source_chain_ids_match = (
        bool(runner.get("runner_readiness_id"))
        and runner.get("runner_readiness_id") == future_plan.get("runner_readiness_id")
        and runner.get("runner_readiness_id")
        == execution_plan_binding.get("source_runner_readiness_id")
        and execution_plan_binding.get("execution_plan_binding_id")
        == future_plan.get("execution_plan_binding_id")
        and execution_plan_binding.get("execution_plan_binding_id")
        == non_executable_command_artifact.get("source_execution_plan_binding_id")
        and runner.get("source_receipt_closeout_id")
        == execution_plan_binding.get("source_receipt_closeout_id")
        and runner.get("source_dry_run_package_id")
        == execution_plan_binding.get("source_dry_run_package_id")
    )
    receipt_validation_and_parser_carried_forward = (
        result_parser.get("required_command_shape_hash")
        == runner.get("dry_run_command_shape_hash")
        and result_parser.get("execution_required") is False
        and result_parser.get("stdout_allowed") is False
        and result_parser.get("stderr_allowed") is False
        and result_parser.get("database_apply_authorized") is False
        and validation.get("dry_run_command_shape_hash")
        == runner.get("dry_run_command_shape_hash")
        and validation.get("execution_performed") is False
        and validation.get("stdout_included") is False
        and validation.get("stderr_included") is False
        and validation.get("database_apply_authorized") is False
        and validation.get("executes_endpoint") is False
        and validation.get("executes_sql") is False
        and validation.get("writes_database") is False
    )
    runner_execution_gate_closed = (
        future_plan.get("dry_run_execution_performed") is False
        and future_plan.get("runner_execution_authorized") is False
        and future_plan.get("dry_run_execution_authorized") is False
        and future_plan.get("database_apply_authorized") is False
        and future_plan.get("executes_database_apply") is False
        and future_plan.get("executes_endpoint") is False
        and future_plan.get("executes_sql") is False
        and future_plan.get("writes_database") is False
        and runner.get("runner_execution_authorized") is False
        and runner.get("dry_run_execution_authorized") is False
        and runner.get("database_apply_authorized") is False
        and execution_plan_preview_only
        and non_executable_command_artifact_bound
    )
    target_hash_locked = (
        runner.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(runner.get("expected_sha256"))
        and bool(runner.get("actual_sha256"))
        and runner.get("expected_sha256") == runner.get("actual_sha256")
        and runner.get("hash_matches") is True
        and runner.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    runner_contract_blocks_database_apply = (
        runner_contract.get(
            "permits_future_database_apply_controlled_dry_run_execution_plan_binding"
        )
        is True
        and runner_contract.get("executes_database_apply") is False
        and runner_contract.get("database_apply_authorized") is False
        and runner_contract.get("ready_for_database_apply_now") is False
        and runner_contract.get("signs_database_apply_authorization") is False
        and runner_contract.get("writes_database") is False
    )
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and runner.get("accepts_plaintext_secret") is False
        and runner.get("reads_secret_in_preview") is False
        and runner.get("signature_material_included") is False
        and runner.get("secret_material_included") is False
        and runner.get("signs_database_apply_authorization") is False
        and runner.get("executes_authorization_evidence") is False
        and runner.get("executes_database_apply") is False
        and runner.get("executes_endpoint_in_preview") is False
        and runner.get("executes_sql_in_preview") is False
        and runner.get("writes_database_in_preview") is False
        and receipt_validation_and_parser_carried_forward
        and execution_plan_preview_only
        and non_executable_command_artifact_bound
    )
    checks = [
        _controlled_dry_run_execution_plan_closeout_check(
            "runner_readiness_ready",
            runner_readiness_result.get("result")
            == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_READY"
            and future_plan.get(
                "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding"
            )
            is True
            and future_plan.get(
                "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout"
            )
            is True
            and runner.get(
                "ready_for_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True,
            {
                "result": runner_readiness_result.get("result"),
                "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding": (
                    future_plan.get(
                        "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout": (
                    future_plan.get(
                        "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout"
                    )
                ),
            },
            "wait_for_controlled_dry_run_runner_readiness",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "runner_readiness_id": runner.get("runner_readiness_id"),
                "execution_plan_binding_id": execution_plan_binding.get(
                    "execution_plan_binding_id"
                ),
                "artifact_source_execution_plan_binding_id": (
                    non_executable_command_artifact.get(
                        "source_execution_plan_binding_id"
                    )
                ),
            },
            "wait_for_execution_plan_source_chain_ids",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "execution_plan_closeout_contract_complete",
            len(execution_plan_closeout_fields) == 12
            and len(execution_plan_closeout_acceptance_gates) == 10
            and len(non_executable_command_artifact_fields) == 10
            and "non_executable_command_artifact_id"
            in execution_plan_closeout_fields
            and "non_executable_command_artifact_bound"
            in execution_plan_closeout_acceptance_gates,
            {
                "execution_plan_closeout_field_count": len(
                    execution_plan_closeout_fields
                ),
                "execution_plan_closeout_acceptance_gate_count": len(
                    execution_plan_closeout_acceptance_gates
                ),
                "non_executable_command_artifact_field_count": len(
                    non_executable_command_artifact_fields
                ),
            },
            "wait_for_execution_plan_closeout_contract",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "execution_plan_binding_preview_only",
            execution_plan_preview_only,
            {
                "execution_authorized": execution_plan_binding.get(
                    "execution_authorized"
                ),
                "runner_execution_authorized": execution_plan_binding.get(
                    "runner_execution_authorized"
                ),
                "database_write_included": execution_plan_binding.get(
                    "database_write_included"
                ),
            },
            "abort_if_execution_plan_binding_is_executable",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "non_executable_command_artifact_bound",
            non_executable_command_artifact_bound,
            {
                "artifact_id": non_executable_command_artifact.get("artifact_id"),
                "command_text_included": non_executable_command_artifact.get(
                    "command_text_included"
                ),
                "argv_included": non_executable_command_artifact.get(
                    "argv_included"
                ),
                "database_write_included": non_executable_command_artifact.get(
                    "database_write_included"
                ),
            },
            "abort_if_command_artifact_contains_executable_material",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "command_artifact_hash_locked",
            command_artifact_hash_locked,
            {
                "artifact_sha256_present": bool(artifact_sha256),
                "artifact_sha256_length": len(artifact_sha256),
                "artifact_id": artifact_id,
            },
            "abort_if_command_artifact_hash_is_not_locked",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "receipt_validation_and_parser_carried_forward",
            receipt_validation_and_parser_carried_forward,
            {
                "parser_id": result_parser.get("parser_id"),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
                "dry_run_command_shape_hash": runner.get(
                    "dry_run_command_shape_hash"
                ),
            },
            "wait_for_receipt_validation_and_parser_carry_forward",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "runner_execution_gate_closed",
            runner_execution_gate_closed,
            {
                "dry_run_execution_performed": future_plan.get(
                    "dry_run_execution_performed"
                ),
                "runner_execution_authorized": future_plan.get(
                    "runner_execution_authorized"
                ),
                "writes_database": future_plan.get("writes_database"),
            },
            "abort_if_runner_execution_gate_opens",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": runner.get("target_file"),
                "expected_sha256_present": bool(runner.get("expected_sha256")),
                "actual_sha256_present": bool(runner.get("actual_sha256")),
                "hash_matches": runner.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "runner_contract_blocks_database_apply",
            runner_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_execution_plan_binding": (
                    runner_contract.get(
                        "permits_future_database_apply_controlled_dry_run_execution_plan_binding"
                    )
                ),
                "database_apply_authorized": runner_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": runner_contract.get("writes_database"),
            },
            "abort_if_runner_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_execution_plan_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "non_executable_command_artifact_bound": (
                    non_executable_command_artifact_bound
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS"
    )
    future_database_apply_controlled_dry_run_command_artifact_verification = {
        "execution_plan_closeout_id": closeout_id,
        "non_executable_command_artifact_id": artifact_id,
        "non_executable_command_artifact_sha256": artifact_sha256,
        "source_runner_readiness_id": runner.get("runner_readiness_id"),
        "source_execution_plan_binding_id": execution_plan_binding.get(
            "execution_plan_binding_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_command_artifact_verification": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_command_artifact_closeout": (
            closeout_ready
        ),
        "execution_plan_closeout_ready": closeout_ready,
        "non_executable_command_artifact_verified": closeout_ready,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_execution_plan_closeout = {
        "execution_plan_closeout_id": closeout_id,
        "authorization_material_type": "controlled_dry_run_execution_plan_closeout",
        "source_runner_readiness_id": runner.get("runner_readiness_id"),
        "source_execution_plan_binding_id": execution_plan_binding.get(
            "execution_plan_binding_id"
        ),
        "source_receipt_closeout_id": runner.get("source_receipt_closeout_id"),
        "source_dry_run_package_id": runner.get("source_dry_run_package_id"),
        "source_controlled_apply_preflight_id": runner.get(
            "source_controlled_apply_preflight_id"
        ),
        "source_dry_run_execution_receipt_id": runner.get(
            "source_dry_run_execution_receipt_id"
        ),
        "dry_run_result_parser_id": runner.get("dry_run_result_parser_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_plan_closeout": (
            closeout_ready
        ),
        "execution_plan_closeout_fields": execution_plan_closeout_fields,
        "execution_plan_closeout_field_count": len(
            execution_plan_closeout_fields
        ),
        "execution_plan_closeout_acceptance_gates": (
            execution_plan_closeout_acceptance_gates
        ),
        "execution_plan_closeout_acceptance_gate_count": len(
            execution_plan_closeout_acceptance_gates
        ),
        "non_executable_command_artifact": non_executable_command_artifact,
        "non_executable_command_artifact_count": 1,
        "non_executable_command_artifact_field_count": len(
            non_executable_command_artifact_fields
        ),
        "non_executable_command_artifact_sha256": artifact_sha256,
        "execution_plan_binding": execution_plan_binding,
        "execution_plan_binding_count": 1,
        "execution_plan_binding_field_count": runner.get(
            "execution_plan_binding_field_count", 0
        ),
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "dry_run_command_shape_hash": runner.get("dry_run_command_shape_hash"),
        "target_file": runner.get("target_file"),
        "expected_sha256": runner.get("expected_sha256"),
        "actual_sha256": runner.get("actual_sha256"),
        "hash_matches": runner.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "execution_plan_closeout_only": True,
        "non_executable_command_artifact_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_execution_plan_closeout_contract = {
        "mode": "controlled_dry_run_execution_plan_closeout_and_non_executable_command_artifact_verification_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-execution-plan-closeout"
        ),
        "source_runner_readiness_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-runner-readiness"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_command_artifact_verification": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(runner_readiness_result.get("success")),
        "generated_at": runner_readiness_result.get("generated_at"),
        "source_policy": runner_readiness_result.get("policy"),
        "stats": runner_readiness_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_execution_plan_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_execution_plan_closeout_check_count": len(checks),
            "controlled_dry_run_execution_plan_closeout_pass_count": passed_count,
            "controlled_dry_run_execution_plan_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_runner_readiness_ready_count": summary.get(
                "controlled_dry_run_runner_readiness_ready_count", 0
            ),
            "controlled_dry_run_runner_readiness_check_count": summary.get(
                "controlled_dry_run_runner_readiness_check_count", 0
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_execution_plan_closeout_count": 1,
            "controlled_dry_run_execution_plan_closeout_field_count": len(
                execution_plan_closeout_fields
            ),
            "controlled_dry_run_execution_plan_closeout_acceptance_gate_count": len(
                execution_plan_closeout_acceptance_gates
            ),
            "non_executable_command_artifact_count": 1,
            "non_executable_command_artifact_field_count": len(
                non_executable_command_artifact_fields
            ),
            "execution_plan_binding_count": summary.get(
                "execution_plan_binding_count", 0
            ),
            "execution_plan_binding_field_count": summary.get(
                "execution_plan_binding_field_count", 0
            ),
            "controlled_dry_run_runner_readiness_count": summary.get(
                "controlled_dry_run_runner_readiness_count", 0
            ),
            "controlled_dry_run_runner_readiness_field_count": summary.get(
                "controlled_dry_run_runner_readiness_field_count", 0
            ),
            "controlled_dry_run_runner_readiness_acceptance_gate_count": (
                summary.get(
                    "controlled_dry_run_runner_readiness_acceptance_gate_count", 0
                )
            ),
            "dry_run_result_parser_count": summary.get(
                "dry_run_result_parser_count", 0
            ),
            "dry_run_result_parser_field_count": summary.get(
                "dry_run_result_parser_field_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "controlled_dry_run_receipt_closeout_count": summary.get(
                "controlled_dry_run_receipt_closeout_count", 0
            ),
            "controlled_dry_run_receipt_closeout_field_count": summary.get(
                "controlled_dry_run_receipt_closeout_field_count", 0
            ),
            "controlled_dry_run_receipt_closeout_acceptance_gate_count": summary.get(
                "controlled_dry_run_receipt_closeout_acceptance_gate_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_command_artifact_verification": (
            future_database_apply_controlled_dry_run_command_artifact_verification
        ),
        "controlled_dry_run_execution_plan_closeout": (
            controlled_dry_run_execution_plan_closeout
        ),
        "controlled_dry_run_execution_plan_closeout_contract": (
            controlled_dry_run_execution_plan_closeout_contract
        ),
        "controlled_dry_run_execution_plan_closeout_checks": checks,
        "source_controlled_dry_run_runner_readiness_summary": summary,
        "source_controlled_dry_run_runner_readiness_contract": runner_contract,
        "source_controlled_dry_run_runner_readiness": runner,
        "source_database_apply_controlled_dry_run_execution_plan_binding": future_plan,
        "safety": {
            "read_only_db_apply_controlled_dry_run_execution_plan_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run command artifact closeout.",
            "Keep command artifacts hash-locked and non-executable before any runner execution receipt lane.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out a non-executable command artifact into a receipt preflight."""
    execution_plan_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_artifact = (
        execution_plan_closeout_result.get(
            "future_database_apply_controlled_dry_run_command_artifact_verification"
        )
        or {}
    )
    plan_closeout = (
        execution_plan_closeout_result.get(
            "controlled_dry_run_execution_plan_closeout"
        )
        or {}
    )
    plan_closeout_contract = (
        execution_plan_closeout_result.get(
            "controlled_dry_run_execution_plan_closeout_contract"
        )
        or {}
    )
    summary = execution_plan_closeout_result.get("summary") or {}
    safety = execution_plan_closeout_result.get("safety") or {}
    artifact = plan_closeout.get("non_executable_command_artifact") or {}
    execution_plan_binding = plan_closeout.get("execution_plan_binding") or {}
    validation = plan_closeout.get("receipt_validation_report") or {}
    result_parser = plan_closeout.get("dry_run_result_parser") or {}
    rollback_binding = plan_closeout.get("rollback_binding") or {}
    verifier_binding = plan_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_command_artifact_closeout_id(
        execution_plan_closeout_result
    )
    receipt_preflight_id = f"{closeout_id}-runner-execution-receipt-preflight"
    command_artifact_closeout_fields = [
        "command_artifact_closeout_id",
        "source_execution_plan_closeout_id",
        "source_non_executable_command_artifact_id",
        "source_execution_plan_binding_id",
        "source_runner_readiness_id",
        "source_receipt_closeout_id",
        "dry_run_command_shape_hash",
        "non_executable_command_artifact_sha256",
        "runner_execution_receipt_preflight_id",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "abort_conditions",
    ]
    command_artifact_closeout_acceptance_gates = [
        "execution_plan_closeout_ready",
        "source_chain_ids_match",
        "non_executable_command_artifact_hash_verified",
        "non_executable_artifact_has_no_command_text_or_argv",
        "runner_execution_receipt_preflight_bound",
        "runner_execution_receipt_preflight_no_execute",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "execution_plan_closeout_contract_blocks_database_apply",
        "no_secret_signature_or_database_apply",
    ]
    runner_execution_receipt_preflight_fields = [
        "preflight_id",
        "source_command_artifact_closeout_id",
        "source_non_executable_command_artifact_id",
        "dry_run_command_shape_hash",
        "preflight_status",
        "execution_required",
        "stdout_capture_allowed",
        "stderr_capture_allowed",
        "database_apply_authorized",
        "writes_database",
    ]
    abort_conditions = [
        "abort_if_execution_plan_closeout_not_ready",
        "abort_if_non_executable_command_artifact_hash_changes",
        "abort_if_command_artifact_contains_command_text_or_argv",
        "abort_if_runner_execution_receipt_preflight_requests_execution",
        "abort_if_stdout_or_stderr_capture_is_requested_before_execution_lane",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_endpoint_sql_database_write_or_signature_is_requested",
    ]
    command_artifact_hash_verified = (
        bool(artifact.get("non_executable_command_artifact_sha256"))
        and artifact.get("non_executable_command_artifact_sha256")
        == plan_closeout.get("non_executable_command_artifact_sha256")
        == future_artifact.get("non_executable_command_artifact_sha256")
        and len(str(artifact.get("non_executable_command_artifact_sha256") or ""))
        == 64
    )
    non_executable_artifact_has_no_command_text_or_argv = (
        artifact.get("artifact_type") == "non_executable_command_artifact_reference"
        and artifact.get("command_text_included") is False
        and artifact.get("argv_included") is False
        and artifact.get("command_text") is None
        and artifact.get("argv") is None
        and artifact.get("shell_command_included") is False
        and artifact.get("endpoint_execution_included") is False
        and artifact.get("sql_execution_included") is False
        and artifact.get("database_write_included") is False
        and artifact.get("stdout_capture_allowed") is False
        and artifact.get("stderr_capture_allowed") is False
        and artifact.get("execution_authorized") is False
        and artifact.get("dry_run_execution_authorized") is False
        and artifact.get("runner_execution_authorized") is False
        and artifact.get("database_apply_authorized") is False
    )
    runner_execution_receipt_preflight = {
        "preflight_id": receipt_preflight_id,
        "source_command_artifact_closeout_id": closeout_id,
        "source_execution_plan_closeout_id": plan_closeout.get(
            "execution_plan_closeout_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "source_execution_plan_binding_id": artifact.get(
            "source_execution_plan_binding_id"
        ),
        "source_runner_readiness_id": artifact.get("source_runner_readiness_id"),
        "source_receipt_closeout_id": artifact.get("source_receipt_closeout_id"),
        "source_dry_run_package_id": artifact.get("source_dry_run_package_id"),
        "dry_run_command_shape_hash": artifact.get("dry_run_command_shape_hash"),
        "non_executable_command_artifact_sha256": artifact.get(
            "non_executable_command_artifact_sha256"
        ),
        "preflight_status": "preflight_only_not_executed",
        "execution_required": False,
        "execution_authorized": False,
        "dry_run_execution_authorized": False,
        "runner_execution_authorized": False,
        "shell_execution_included": False,
        "endpoint_execution_included": False,
        "sql_execution_included": False,
        "database_write_included": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "execution_performed": False,
        "stdout_included": False,
        "stderr_included": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "writes_database": False,
        "runner_execution_receipt_preflight_field_count": len(
            runner_execution_receipt_preflight_fields
        ),
        "runner_execution_receipt_preflight_fields": (
            runner_execution_receipt_preflight_fields
        ),
    }
    runner_execution_receipt_preflight_bound = (
        bool(runner_execution_receipt_preflight.get("preflight_id"))
        and runner_execution_receipt_preflight.get(
            "source_command_artifact_closeout_id"
        )
        == closeout_id
        and runner_execution_receipt_preflight.get(
            "source_non_executable_command_artifact_id"
        )
        == artifact.get("artifact_id")
        and runner_execution_receipt_preflight.get(
            "source_execution_plan_binding_id"
        )
        == execution_plan_binding.get("execution_plan_binding_id")
        and runner_execution_receipt_preflight.get("dry_run_command_shape_hash")
        == plan_closeout.get("dry_run_command_shape_hash")
        and int(
            runner_execution_receipt_preflight.get(
                "runner_execution_receipt_preflight_field_count"
            )
            or 0
        )
        == 10
    )
    runner_execution_receipt_preflight_no_execute = (
        runner_execution_receipt_preflight.get("preflight_status")
        == "preflight_only_not_executed"
        and runner_execution_receipt_preflight.get("execution_required") is False
        and runner_execution_receipt_preflight.get("execution_authorized") is False
        and runner_execution_receipt_preflight.get("dry_run_execution_authorized")
        is False
        and runner_execution_receipt_preflight.get("runner_execution_authorized")
        is False
        and runner_execution_receipt_preflight.get("shell_execution_included")
        is False
        and runner_execution_receipt_preflight.get("endpoint_execution_included")
        is False
        and runner_execution_receipt_preflight.get("sql_execution_included") is False
        and runner_execution_receipt_preflight.get("database_write_included")
        is False
        and runner_execution_receipt_preflight.get("stdout_capture_allowed") is False
        and runner_execution_receipt_preflight.get("stderr_capture_allowed") is False
        and runner_execution_receipt_preflight.get("execution_performed") is False
        and runner_execution_receipt_preflight.get("stdout_included") is False
        and runner_execution_receipt_preflight.get("stderr_included") is False
        and runner_execution_receipt_preflight.get("database_apply_authorized")
        is False
        and runner_execution_receipt_preflight.get("writes_database") is False
    )
    source_chain_ids_match = (
        bool(plan_closeout.get("execution_plan_closeout_id"))
        and plan_closeout.get("execution_plan_closeout_id")
        == future_artifact.get("execution_plan_closeout_id")
        and plan_closeout.get("execution_plan_closeout_id")
        == runner_execution_receipt_preflight.get(
            "source_execution_plan_closeout_id"
        )
        and artifact.get("artifact_id")
        == future_artifact.get("non_executable_command_artifact_id")
        == runner_execution_receipt_preflight.get(
            "source_non_executable_command_artifact_id"
        )
        and artifact.get("source_execution_plan_binding_id")
        == plan_closeout.get("source_execution_plan_binding_id")
        == execution_plan_binding.get("execution_plan_binding_id")
        and artifact.get("source_runner_readiness_id")
        == plan_closeout.get("source_runner_readiness_id")
    )
    result_parser_and_validation_carried_forward = (
        result_parser.get("required_command_shape_hash")
        == plan_closeout.get("dry_run_command_shape_hash")
        and result_parser.get("execution_required") is False
        and result_parser.get("stdout_allowed") is False
        and result_parser.get("stderr_allowed") is False
        and result_parser.get("database_apply_authorized") is False
        and validation.get("dry_run_command_shape_hash")
        == plan_closeout.get("dry_run_command_shape_hash")
        and validation.get("execution_performed") is False
        and validation.get("stdout_included") is False
        and validation.get("stderr_included") is False
        and validation.get("database_apply_authorized") is False
        and validation.get("executes_endpoint") is False
        and validation.get("executes_sql") is False
        and validation.get("writes_database") is False
    )
    target_hash_locked = (
        plan_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(plan_closeout.get("expected_sha256"))
        and bool(plan_closeout.get("actual_sha256"))
        and plan_closeout.get("expected_sha256")
        == plan_closeout.get("actual_sha256")
        and plan_closeout.get("hash_matches") is True
        and plan_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    plan_closeout_contract_blocks_database_apply = (
        plan_closeout_contract.get(
            "permits_future_database_apply_controlled_dry_run_command_artifact_verification"
        )
        is True
        and plan_closeout_contract.get("executes_database_apply") is False
        and plan_closeout_contract.get("database_apply_authorized") is False
        and plan_closeout_contract.get("ready_for_database_apply_now") is False
        and plan_closeout_contract.get("signs_database_apply_authorization") is False
        and plan_closeout_contract.get("writes_database") is False
    )
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and plan_closeout.get("accepts_plaintext_secret") is False
        and plan_closeout.get("reads_secret_in_preview") is False
        and plan_closeout.get("signature_material_included") is False
        and plan_closeout.get("secret_material_included") is False
        and plan_closeout.get("signs_database_apply_authorization") is False
        and plan_closeout.get("executes_authorization_evidence") is False
        and plan_closeout.get("executes_database_apply") is False
        and plan_closeout.get("executes_endpoint_in_preview") is False
        and plan_closeout.get("executes_sql_in_preview") is False
        and plan_closeout.get("writes_database_in_preview") is False
        and non_executable_artifact_has_no_command_text_or_argv
        and runner_execution_receipt_preflight_no_execute
        and result_parser_and_validation_carried_forward
    )
    checks = [
        _controlled_dry_run_command_artifact_closeout_check(
            "execution_plan_closeout_ready",
            execution_plan_closeout_result.get("result")
            == "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT_READY"
            and future_artifact.get(
                "ready_for_future_database_apply_controlled_dry_run_command_artifact_verification"
            )
            is True
            and future_artifact.get(
                "can_enter_future_database_apply_controlled_dry_run_command_artifact_closeout"
            )
            is True
            and plan_closeout.get(
                "ready_for_future_database_apply_controlled_dry_run_execution_plan_closeout"
            )
            is True,
            {
                "result": execution_plan_closeout_result.get("result"),
                "ready_for_future_database_apply_controlled_dry_run_command_artifact_verification": (
                    future_artifact.get(
                        "ready_for_future_database_apply_controlled_dry_run_command_artifact_verification"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_command_artifact_closeout": (
                    future_artifact.get(
                        "can_enter_future_database_apply_controlled_dry_run_command_artifact_closeout"
                    )
                ),
            },
            "wait_for_controlled_dry_run_execution_plan_closeout",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "execution_plan_closeout_id": plan_closeout.get(
                    "execution_plan_closeout_id"
                ),
                "artifact_id": artifact.get("artifact_id"),
                "runner_execution_receipt_preflight_id": receipt_preflight_id,
            },
            "wait_for_command_artifact_source_chain_ids",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "command_artifact_closeout_contract_complete",
            len(command_artifact_closeout_fields) == 12
            and len(command_artifact_closeout_acceptance_gates) == 10
            and len(runner_execution_receipt_preflight_fields) == 10
            and "runner_execution_receipt_preflight_id"
            in command_artifact_closeout_fields
            and "runner_execution_receipt_preflight_no_execute"
            in command_artifact_closeout_acceptance_gates,
            {
                "command_artifact_closeout_field_count": len(
                    command_artifact_closeout_fields
                ),
                "command_artifact_closeout_acceptance_gate_count": len(
                    command_artifact_closeout_acceptance_gates
                ),
                "runner_execution_receipt_preflight_field_count": len(
                    runner_execution_receipt_preflight_fields
                ),
            },
            "wait_for_command_artifact_closeout_contract",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "non_executable_command_artifact_hash_verified",
            command_artifact_hash_verified,
            {
                "artifact_sha256_present": bool(
                    artifact.get("non_executable_command_artifact_sha256")
                ),
                "artifact_sha256_length": len(
                    str(artifact.get("non_executable_command_artifact_sha256") or "")
                ),
            },
            "abort_if_command_artifact_hash_changes",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "non_executable_artifact_has_no_command_text_or_argv",
            non_executable_artifact_has_no_command_text_or_argv,
            {
                "command_text_included": artifact.get("command_text_included"),
                "argv_included": artifact.get("argv_included"),
                "shell_command_included": artifact.get("shell_command_included"),
                "database_write_included": artifact.get("database_write_included"),
            },
            "abort_if_command_artifact_contains_executable_material",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "runner_execution_receipt_preflight_bound",
            runner_execution_receipt_preflight_bound,
            {
                "preflight_id": runner_execution_receipt_preflight.get(
                    "preflight_id"
                ),
                "source_non_executable_command_artifact_id": (
                    runner_execution_receipt_preflight.get(
                        "source_non_executable_command_artifact_id"
                    )
                ),
                "runner_execution_receipt_preflight_field_count": (
                    runner_execution_receipt_preflight.get(
                        "runner_execution_receipt_preflight_field_count"
                    )
                ),
            },
            "wait_for_runner_execution_receipt_preflight_binding",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "runner_execution_receipt_preflight_no_execute",
            runner_execution_receipt_preflight_no_execute,
            {
                "execution_required": runner_execution_receipt_preflight.get(
                    "execution_required"
                ),
                "execution_authorized": runner_execution_receipt_preflight.get(
                    "execution_authorized"
                ),
                "stdout_capture_allowed": runner_execution_receipt_preflight.get(
                    "stdout_capture_allowed"
                ),
                "writes_database": runner_execution_receipt_preflight.get(
                    "writes_database"
                ),
            },
            "abort_if_runner_execution_receipt_preflight_executes",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "result_parser_and_receipt_validation_carried_forward",
            result_parser_and_validation_carried_forward,
            {
                "parser_id": result_parser.get("parser_id"),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
                "dry_run_command_shape_hash": plan_closeout.get(
                    "dry_run_command_shape_hash"
                ),
            },
            "wait_for_result_parser_and_receipt_validation_carry_forward",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": plan_closeout.get("target_file"),
                "expected_sha256_present": bool(plan_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(plan_closeout.get("actual_sha256")),
                "hash_matches": plan_closeout.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "execution_plan_closeout_contract_blocks_database_apply",
            plan_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_command_artifact_verification": (
                    plan_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_command_artifact_verification"
                    )
                ),
                "database_apply_authorized": plan_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": plan_closeout_contract.get("writes_database"),
            },
            "abort_if_execution_plan_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_command_artifact_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "runner_execution_receipt_preflight_no_execute": (
                    runner_execution_receipt_preflight_no_execute
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_runner_execution_receipt_preflight = {
        "command_artifact_closeout_id": closeout_id,
        "runner_execution_receipt_preflight_id": receipt_preflight_id,
        "source_execution_plan_closeout_id": plan_closeout.get(
            "execution_plan_closeout_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "source_execution_plan_binding_id": artifact.get(
            "source_execution_plan_binding_id"
        ),
        "non_executable_command_artifact_sha256": artifact.get(
            "non_executable_command_artifact_sha256"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout": (
            closeout_ready
        ),
        "command_artifact_closeout_ready": closeout_ready,
        "runner_execution_receipt_preflight_bound": closeout_ready,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_command_artifact_closeout = {
        "command_artifact_closeout_id": closeout_id,
        "authorization_material_type": "controlled_dry_run_command_artifact_closeout",
        "source_execution_plan_closeout_id": plan_closeout.get(
            "execution_plan_closeout_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "source_execution_plan_binding_id": artifact.get(
            "source_execution_plan_binding_id"
        ),
        "source_runner_readiness_id": artifact.get("source_runner_readiness_id"),
        "source_receipt_closeout_id": artifact.get("source_receipt_closeout_id"),
        "source_dry_run_package_id": artifact.get("source_dry_run_package_id"),
        "dry_run_command_shape_hash": artifact.get("dry_run_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_command_artifact_closeout": (
            closeout_ready
        ),
        "command_artifact_closeout_fields": command_artifact_closeout_fields,
        "command_artifact_closeout_field_count": len(
            command_artifact_closeout_fields
        ),
        "command_artifact_closeout_acceptance_gates": (
            command_artifact_closeout_acceptance_gates
        ),
        "command_artifact_closeout_acceptance_gate_count": len(
            command_artifact_closeout_acceptance_gates
        ),
        "runner_execution_receipt_preflight": (
            runner_execution_receipt_preflight
        ),
        "runner_execution_receipt_preflight_count": 1,
        "runner_execution_receipt_preflight_field_count": len(
            runner_execution_receipt_preflight_fields
        ),
        "non_executable_command_artifact": artifact,
        "non_executable_command_artifact_count": 1,
        "non_executable_command_artifact_field_count": plan_closeout.get(
            "non_executable_command_artifact_field_count", 0
        ),
        "non_executable_command_artifact_sha256": artifact.get(
            "non_executable_command_artifact_sha256"
        ),
        "execution_plan_binding": execution_plan_binding,
        "execution_plan_binding_count": 1,
        "execution_plan_binding_field_count": plan_closeout.get(
            "execution_plan_binding_field_count", 0
        ),
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "target_file": plan_closeout.get("target_file"),
        "expected_sha256": plan_closeout.get("expected_sha256"),
        "actual_sha256": plan_closeout.get("actual_sha256"),
        "hash_matches": plan_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "command_artifact_closeout_only": True,
        "runner_execution_receipt_preflight_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_command_artifact_closeout_contract = {
        "mode": "controlled_dry_run_command_artifact_closeout_and_runner_execution_receipt_preflight_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-command-artifact-closeout"
        ),
        "source_execution_plan_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-execution-plan-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(execution_plan_closeout_result.get("success")),
        "generated_at": execution_plan_closeout_result.get("generated_at"),
        "source_policy": execution_plan_closeout_result.get("policy"),
        "stats": execution_plan_closeout_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_command_artifact_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_command_artifact_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_command_artifact_closeout_pass_count": passed_count,
            "controlled_dry_run_command_artifact_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_execution_plan_closeout_ready_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_ready_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_check_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_check_count", 0
            ),
            "controlled_dry_run_runner_readiness_ready_count": summary.get(
                "controlled_dry_run_runner_readiness_ready_count", 0
            ),
            "controlled_dry_run_runner_readiness_check_count": summary.get(
                "controlled_dry_run_runner_readiness_check_count", 0
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_command_artifact_closeout_count": 1,
            "controlled_dry_run_command_artifact_closeout_field_count": len(
                command_artifact_closeout_fields
            ),
            "controlled_dry_run_command_artifact_closeout_acceptance_gate_count": len(
                command_artifact_closeout_acceptance_gates
            ),
            "runner_execution_receipt_preflight_count": 1,
            "runner_execution_receipt_preflight_field_count": len(
                runner_execution_receipt_preflight_fields
            ),
            "controlled_dry_run_execution_plan_closeout_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_field_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_field_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_acceptance_gate_count": (
                summary.get(
                    "controlled_dry_run_execution_plan_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "non_executable_command_artifact_count": summary.get(
                "non_executable_command_artifact_count", 0
            ),
            "non_executable_command_artifact_field_count": summary.get(
                "non_executable_command_artifact_field_count", 0
            ),
            "execution_plan_binding_count": summary.get(
                "execution_plan_binding_count", 0
            ),
            "execution_plan_binding_field_count": summary.get(
                "execution_plan_binding_field_count", 0
            ),
            "dry_run_result_parser_count": summary.get(
                "dry_run_result_parser_count", 0
            ),
            "dry_run_result_parser_field_count": summary.get(
                "dry_run_result_parser_field_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
            future_database_apply_controlled_dry_run_runner_execution_receipt_preflight
        ),
        "controlled_dry_run_command_artifact_closeout": (
            controlled_dry_run_command_artifact_closeout
        ),
        "controlled_dry_run_command_artifact_closeout_contract": (
            controlled_dry_run_command_artifact_closeout_contract
        ),
        "controlled_dry_run_command_artifact_closeout_checks": checks,
        "source_controlled_dry_run_execution_plan_closeout_summary": summary,
        "source_controlled_dry_run_execution_plan_closeout_contract": (
            plan_closeout_contract
        ),
        "source_controlled_dry_run_execution_plan_closeout": plan_closeout,
        "source_database_apply_controlled_dry_run_command_artifact_verification": (
            future_artifact
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_command_artifact_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run runner execution receipt closeout.",
            "Keep runner execution receipt preflight non-executing until the dedicated receipt lane is explicit.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the runner receipt preflight without running the runner."""
    command_artifact_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_preflight = (
        command_artifact_closeout_result.get(
            "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
        )
        or {}
    )
    command_closeout = (
        command_artifact_closeout_result.get(
            "controlled_dry_run_command_artifact_closeout"
        )
        or {}
    )
    command_closeout_contract = (
        command_artifact_closeout_result.get(
            "controlled_dry_run_command_artifact_closeout_contract"
        )
        or {}
    )
    summary = command_artifact_closeout_result.get("summary") or {}
    safety = command_artifact_closeout_result.get("safety") or {}
    receipt_preflight = command_closeout.get("runner_execution_receipt_preflight") or {}
    artifact = command_closeout.get("non_executable_command_artifact") or {}
    execution_plan_binding = command_closeout.get("execution_plan_binding") or {}
    validation = command_closeout.get("receipt_validation_report") or {}
    result_parser = command_closeout.get("dry_run_result_parser") or {}
    rollback_binding = command_closeout.get("rollback_binding") or {}
    verifier_binding = command_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_runner_execution_receipt_closeout_id(
        command_artifact_closeout_result
    )
    parser_verification_id = f"{closeout_id}-post-receipt-parser-verification"
    runner_execution_receipt_closeout_fields = [
        "runner_execution_receipt_closeout_id",
        "source_command_artifact_closeout_id",
        "source_runner_execution_receipt_preflight_id",
        "source_non_executable_command_artifact_id",
        "source_execution_plan_closeout_id",
        "dry_run_command_shape_hash",
        "non_executable_command_artifact_sha256",
        "post_receipt_parser_verification_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "abort_conditions",
    ]
    runner_execution_receipt_closeout_acceptance_gates = [
        "command_artifact_closeout_ready",
        "source_chain_ids_match",
        "runner_execution_receipt_preflight_no_execute",
        "post_receipt_parser_verification_bound",
        "post_receipt_parser_blocks_execution",
        "receipt_closeout_preview_only",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "command_artifact_closeout_contract_blocks_database_apply",
        "no_secret_signature_or_database_apply",
    ]
    post_receipt_parser_verification_fields = [
        "verification_id",
        "source_runner_execution_receipt_preflight_id",
        "source_command_artifact_closeout_id",
        "expected_preflight_status",
        "expected_execution_performed",
        "expected_stdout_included",
        "expected_stderr_included",
        "required_command_shape_hash",
        "execution_required",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_command_artifact_closeout_not_ready",
        "abort_if_runner_execution_receipt_preflight_requests_execution",
        "abort_if_receipt_closeout_includes_stdout_or_stderr",
        "abort_if_post_receipt_parser_requires_execution",
        "abort_if_command_shape_hash_mismatch",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_endpoint_sql_database_write_or_signature_is_requested",
    ]
    receipt_closeout_preview = {
        "runner_execution_receipt_closeout_id": closeout_id,
        "source_command_artifact_closeout_id": command_closeout.get(
            "command_artifact_closeout_id"
        ),
        "source_runner_execution_receipt_preflight_id": receipt_preflight.get(
            "preflight_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "source_execution_plan_closeout_id": command_closeout.get(
            "source_execution_plan_closeout_id"
        ),
        "dry_run_command_shape_hash": command_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "non_executable_command_artifact_sha256": artifact.get(
            "non_executable_command_artifact_sha256"
        ),
        "receipt_status": "receipt_closeout_preview_not_executed",
        "execution_required": False,
        "execution_authorized": False,
        "dry_run_execution_authorized": False,
        "runner_execution_authorized": False,
        "execution_performed": False,
        "stdout_included": False,
        "stderr_included": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "writes_database": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "receipt_closeout_preview_field_count": 10,
    }
    post_receipt_parser_verification = {
        "verification_id": parser_verification_id,
        "source_runner_execution_receipt_closeout_id": closeout_id,
        "source_runner_execution_receipt_preflight_id": receipt_preflight.get(
            "preflight_id"
        ),
        "source_command_artifact_closeout_id": command_closeout.get(
            "command_artifact_closeout_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "expected_preflight_status": "preflight_only_not_executed",
        "expected_receipt_status": "receipt_closeout_preview_not_executed",
        "expected_execution_performed": False,
        "expected_stdout_included": False,
        "expected_stderr_included": False,
        "required_command_shape_hash": command_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "execution_required": False,
        "stdout_allowed": False,
        "stderr_allowed": False,
        "database_apply_authorized": False,
        "parser_verification_status": "post_receipt_parser_preview_ready",
        "post_receipt_parser_verification_field_count": len(
            post_receipt_parser_verification_fields
        ),
        "post_receipt_parser_verification_fields": (
            post_receipt_parser_verification_fields
        ),
    }
    runner_execution_receipt_preflight_no_execute = (
        receipt_preflight.get("preflight_status") == "preflight_only_not_executed"
        and receipt_preflight.get("execution_required") is False
        and receipt_preflight.get("execution_authorized") is False
        and receipt_preflight.get("dry_run_execution_authorized") is False
        and receipt_preflight.get("runner_execution_authorized") is False
        and receipt_preflight.get("shell_execution_included") is False
        and receipt_preflight.get("endpoint_execution_included") is False
        and receipt_preflight.get("sql_execution_included") is False
        and receipt_preflight.get("database_write_included") is False
        and receipt_preflight.get("stdout_capture_allowed") is False
        and receipt_preflight.get("stderr_capture_allowed") is False
        and receipt_preflight.get("execution_performed") is False
        and receipt_preflight.get("stdout_included") is False
        and receipt_preflight.get("stderr_included") is False
        and receipt_preflight.get("database_apply_authorized") is False
        and receipt_preflight.get("writes_database") is False
    )
    post_receipt_parser_verification_bound = (
        bool(post_receipt_parser_verification.get("verification_id"))
        and post_receipt_parser_verification.get(
            "source_runner_execution_receipt_preflight_id"
        )
        == receipt_preflight.get("preflight_id")
        and post_receipt_parser_verification.get(
            "source_command_artifact_closeout_id"
        )
        == command_closeout.get("command_artifact_closeout_id")
        and post_receipt_parser_verification.get("required_command_shape_hash")
        == command_closeout.get("dry_run_command_shape_hash")
        and int(
            post_receipt_parser_verification.get(
                "post_receipt_parser_verification_field_count"
            )
            or 0
        )
        == 10
    )
    post_receipt_parser_blocks_execution = (
        post_receipt_parser_verification.get("expected_preflight_status")
        == "preflight_only_not_executed"
        and post_receipt_parser_verification.get("expected_receipt_status")
        == "receipt_closeout_preview_not_executed"
        and post_receipt_parser_verification.get("expected_execution_performed")
        is False
        and post_receipt_parser_verification.get("expected_stdout_included")
        is False
        and post_receipt_parser_verification.get("expected_stderr_included")
        is False
        and post_receipt_parser_verification.get("execution_required") is False
        and post_receipt_parser_verification.get("stdout_allowed") is False
        and post_receipt_parser_verification.get("stderr_allowed") is False
        and post_receipt_parser_verification.get("database_apply_authorized")
        is False
    )
    receipt_closeout_preview_only = (
        receipt_closeout_preview.get("receipt_status")
        == "receipt_closeout_preview_not_executed"
        and receipt_closeout_preview.get("execution_required") is False
        and receipt_closeout_preview.get("execution_authorized") is False
        and receipt_closeout_preview.get("dry_run_execution_authorized") is False
        and receipt_closeout_preview.get("runner_execution_authorized") is False
        and receipt_closeout_preview.get("execution_performed") is False
        and receipt_closeout_preview.get("stdout_included") is False
        and receipt_closeout_preview.get("stderr_included") is False
        and receipt_closeout_preview.get("stdout_capture_allowed") is False
        and receipt_closeout_preview.get("stderr_capture_allowed") is False
        and receipt_closeout_preview.get("database_apply_authorized") is False
        and receipt_closeout_preview.get("writes_database") is False
        and receipt_closeout_preview.get("executes_endpoint") is False
        and receipt_closeout_preview.get("executes_sql") is False
    )
    source_chain_ids_match = (
        bool(command_closeout.get("command_artifact_closeout_id"))
        and command_closeout.get("command_artifact_closeout_id")
        == future_preflight.get("command_artifact_closeout_id")
        == receipt_preflight.get("source_command_artifact_closeout_id")
        == receipt_closeout_preview.get("source_command_artifact_closeout_id")
        and receipt_preflight.get("preflight_id")
        == future_preflight.get("runner_execution_receipt_preflight_id")
        == receipt_closeout_preview.get(
            "source_runner_execution_receipt_preflight_id"
        )
        == post_receipt_parser_verification.get(
            "source_runner_execution_receipt_preflight_id"
        )
        and artifact.get("artifact_id")
        == command_closeout.get("source_non_executable_command_artifact_id")
        == receipt_closeout_preview.get("source_non_executable_command_artifact_id")
    )
    result_parser_and_validation_carried_forward = (
        result_parser.get("required_command_shape_hash")
        == command_closeout.get("dry_run_command_shape_hash")
        and result_parser.get("execution_required") is False
        and result_parser.get("stdout_allowed") is False
        and result_parser.get("stderr_allowed") is False
        and result_parser.get("database_apply_authorized") is False
        and validation.get("dry_run_command_shape_hash")
        == command_closeout.get("dry_run_command_shape_hash")
        and validation.get("execution_performed") is False
        and validation.get("stdout_included") is False
        and validation.get("stderr_included") is False
        and validation.get("database_apply_authorized") is False
        and validation.get("executes_endpoint") is False
        and validation.get("executes_sql") is False
        and validation.get("writes_database") is False
    )
    target_hash_locked = (
        command_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(command_closeout.get("expected_sha256"))
        and bool(command_closeout.get("actual_sha256"))
        and command_closeout.get("expected_sha256")
        == command_closeout.get("actual_sha256")
        and command_closeout.get("hash_matches") is True
        and command_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    command_closeout_contract_blocks_database_apply = (
        command_closeout_contract.get(
            "permits_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
        )
        is True
        and command_closeout_contract.get("executes_database_apply") is False
        and command_closeout_contract.get("database_apply_authorized") is False
        and command_closeout_contract.get("ready_for_database_apply_now") is False
        and command_closeout_contract.get("signs_database_apply_authorization")
        is False
        and command_closeout_contract.get("writes_database") is False
    )
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("writes_artifact_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_migration_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_script") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("signs_database_apply_authorization") is False
        and safety.get("executes_authorization_evidence") is False
        and safety.get("executes_database_apply") is False
        and command_closeout.get("accepts_plaintext_secret") is False
        and command_closeout.get("reads_secret_in_preview") is False
        and command_closeout.get("signature_material_included") is False
        and command_closeout.get("secret_material_included") is False
        and command_closeout.get("signs_database_apply_authorization") is False
        and command_closeout.get("executes_authorization_evidence") is False
        and command_closeout.get("executes_database_apply") is False
        and command_closeout.get("executes_endpoint_in_preview") is False
        and command_closeout.get("executes_sql_in_preview") is False
        and command_closeout.get("writes_database_in_preview") is False
        and runner_execution_receipt_preflight_no_execute
        and post_receipt_parser_blocks_execution
        and receipt_closeout_preview_only
        and result_parser_and_validation_carried_forward
    )
    checks = [
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "command_artifact_closeout_ready",
            command_artifact_closeout_result.get("result")
            == "DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT_READY"
            and future_preflight.get(
                "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
            )
            is True
            and future_preflight.get(
                "can_enter_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout"
            )
            is True
            and command_closeout.get(
                "ready_for_future_database_apply_controlled_dry_run_command_artifact_closeout"
            )
            is True,
            {
                "result": command_artifact_closeout_result.get("result"),
                "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
                    future_preflight.get(
                        "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout": (
                    future_preflight.get(
                        "can_enter_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout"
                    )
                ),
            },
            "wait_for_controlled_dry_run_command_artifact_closeout",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "command_artifact_closeout_id": command_closeout.get(
                    "command_artifact_closeout_id"
                ),
                "runner_execution_receipt_preflight_id": receipt_preflight.get(
                    "preflight_id"
                ),
                "artifact_id": artifact.get("artifact_id"),
            },
            "wait_for_runner_execution_receipt_source_chain_ids",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "runner_execution_receipt_closeout_contract_complete",
            len(runner_execution_receipt_closeout_fields) == 12
            and len(runner_execution_receipt_closeout_acceptance_gates) == 10
            and len(post_receipt_parser_verification_fields) == 10
            and "post_receipt_parser_verification_id"
            in runner_execution_receipt_closeout_fields
            and "post_receipt_parser_verification_bound"
            in runner_execution_receipt_closeout_acceptance_gates,
            {
                "runner_execution_receipt_closeout_field_count": len(
                    runner_execution_receipt_closeout_fields
                ),
                "runner_execution_receipt_closeout_acceptance_gate_count": len(
                    runner_execution_receipt_closeout_acceptance_gates
                ),
                "post_receipt_parser_verification_field_count": len(
                    post_receipt_parser_verification_fields
                ),
            },
            "wait_for_runner_execution_receipt_closeout_contract",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "runner_execution_receipt_preflight_no_execute",
            runner_execution_receipt_preflight_no_execute,
            {
                "execution_required": receipt_preflight.get("execution_required"),
                "execution_authorized": receipt_preflight.get(
                    "execution_authorized"
                ),
                "stdout_capture_allowed": receipt_preflight.get(
                    "stdout_capture_allowed"
                ),
                "writes_database": receipt_preflight.get("writes_database"),
            },
            "abort_if_runner_execution_receipt_preflight_executes",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "post_receipt_parser_verification_bound",
            post_receipt_parser_verification_bound,
            {
                "verification_id": post_receipt_parser_verification.get(
                    "verification_id"
                ),
                "source_runner_execution_receipt_preflight_id": (
                    post_receipt_parser_verification.get(
                        "source_runner_execution_receipt_preflight_id"
                    )
                ),
                "post_receipt_parser_verification_field_count": (
                    post_receipt_parser_verification.get(
                        "post_receipt_parser_verification_field_count"
                    )
                ),
            },
            "wait_for_post_receipt_parser_verification_binding",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "post_receipt_parser_blocks_execution",
            post_receipt_parser_blocks_execution,
            {
                "expected_execution_performed": (
                    post_receipt_parser_verification.get(
                        "expected_execution_performed"
                    )
                ),
                "execution_required": post_receipt_parser_verification.get(
                    "execution_required"
                ),
                "database_apply_authorized": post_receipt_parser_verification.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_post_receipt_parser_requires_execution",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "receipt_closeout_preview_only",
            receipt_closeout_preview_only,
            {
                "receipt_status": receipt_closeout_preview.get("receipt_status"),
                "execution_performed": receipt_closeout_preview.get(
                    "execution_performed"
                ),
                "stdout_included": receipt_closeout_preview.get("stdout_included"),
                "writes_database": receipt_closeout_preview.get("writes_database"),
            },
            "abort_if_receipt_closeout_preview_contains_execution",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "result_parser_and_receipt_validation_carried_forward",
            result_parser_and_validation_carried_forward,
            {
                "parser_id": result_parser.get("parser_id"),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
                "dry_run_command_shape_hash": command_closeout.get(
                    "dry_run_command_shape_hash"
                ),
            },
            "wait_for_result_parser_and_receipt_validation_carry_forward",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": command_closeout.get("target_file"),
                "expected_sha256_present": bool(command_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(command_closeout.get("actual_sha256")),
                "hash_matches": command_closeout.get("hash_matches"),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "command_artifact_closeout_contract_blocks_database_apply",
            command_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
                    command_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
                    )
                ),
                "database_apply_authorized": command_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": command_closeout_contract.get("writes_database"),
            },
            "abort_if_command_artifact_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_runner_execution_receipt_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "receipt_closeout_preview_only": receipt_closeout_preview_only,
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_post_receipt_parser_verification = {
        "runner_execution_receipt_closeout_id": closeout_id,
        "post_receipt_parser_verification_id": parser_verification_id,
        "source_command_artifact_closeout_id": command_closeout.get(
            "command_artifact_closeout_id"
        ),
        "source_runner_execution_receipt_preflight_id": receipt_preflight.get(
            "preflight_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "non_executable_command_artifact_sha256": artifact.get(
            "non_executable_command_artifact_sha256"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_post_receipt_parser_verification": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_post_receipt_parser_closeout": (
            closeout_ready
        ),
        "runner_execution_receipt_closeout_ready": closeout_ready,
        "post_receipt_parser_verification_bound": closeout_ready,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_runner_execution_receipt_closeout = {
        "runner_execution_receipt_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_runner_execution_receipt_closeout"
        ),
        "source_command_artifact_closeout_id": command_closeout.get(
            "command_artifact_closeout_id"
        ),
        "source_runner_execution_receipt_preflight_id": receipt_preflight.get(
            "preflight_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "source_execution_plan_closeout_id": command_closeout.get(
            "source_execution_plan_closeout_id"
        ),
        "source_execution_plan_binding_id": command_closeout.get(
            "source_execution_plan_binding_id"
        ),
        "source_runner_readiness_id": command_closeout.get(
            "source_runner_readiness_id"
        ),
        "source_receipt_closeout_id": command_closeout.get(
            "source_receipt_closeout_id"
        ),
        "source_dry_run_package_id": command_closeout.get("source_dry_run_package_id"),
        "dry_run_command_shape_hash": command_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout": (
            closeout_ready
        ),
        "runner_execution_receipt_closeout_fields": (
            runner_execution_receipt_closeout_fields
        ),
        "runner_execution_receipt_closeout_field_count": len(
            runner_execution_receipt_closeout_fields
        ),
        "runner_execution_receipt_closeout_acceptance_gates": (
            runner_execution_receipt_closeout_acceptance_gates
        ),
        "runner_execution_receipt_closeout_acceptance_gate_count": len(
            runner_execution_receipt_closeout_acceptance_gates
        ),
        "receipt_closeout_preview": receipt_closeout_preview,
        "receipt_closeout_preview_count": 1,
        "post_receipt_parser_verification": post_receipt_parser_verification,
        "post_receipt_parser_verification_count": 1,
        "post_receipt_parser_verification_field_count": len(
            post_receipt_parser_verification_fields
        ),
        "runner_execution_receipt_preflight": receipt_preflight,
        "runner_execution_receipt_preflight_count": 1,
        "non_executable_command_artifact": artifact,
        "non_executable_command_artifact_count": 1,
        "non_executable_command_artifact_sha256": artifact.get(
            "non_executable_command_artifact_sha256"
        ),
        "execution_plan_binding": execution_plan_binding,
        "execution_plan_binding_count": 1,
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "target_file": command_closeout.get("target_file"),
        "expected_sha256": command_closeout.get("expected_sha256"),
        "actual_sha256": command_closeout.get("actual_sha256"),
        "hash_matches": command_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "runner_execution_receipt_closeout_only": True,
        "post_receipt_parser_verification_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_runner_execution_receipt_closeout_contract = {
        "mode": "controlled_dry_run_runner_execution_receipt_closeout_and_post_receipt_parser_verification_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-runner-execution-receipt-closeout"
        ),
        "source_command_artifact_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-command-artifact-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_post_receipt_parser_verification": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(command_artifact_closeout_result.get("success")),
        "generated_at": command_artifact_closeout_result.get("generated_at"),
        "source_policy": command_artifact_closeout_result.get("policy"),
        "stats": command_artifact_closeout_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_runner_execution_receipt_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_command_artifact_closeout_ready_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_ready_count", 0
            ),
            "controlled_dry_run_command_artifact_closeout_check_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_check_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_ready_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_ready_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_check_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_check_count", 0
            ),
            "controlled_dry_run_runner_readiness_ready_count": summary.get(
                "controlled_dry_run_runner_readiness_ready_count", 0
            ),
            "controlled_dry_run_runner_readiness_check_count": summary.get(
                "controlled_dry_run_runner_readiness_check_count", 0
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_count": 1,
            "controlled_dry_run_runner_execution_receipt_closeout_field_count": len(
                runner_execution_receipt_closeout_fields
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_acceptance_gate_count": len(
                runner_execution_receipt_closeout_acceptance_gates
            ),
            "post_receipt_parser_verification_count": 1,
            "post_receipt_parser_verification_field_count": len(
                post_receipt_parser_verification_fields
            ),
            "receipt_closeout_preview_count": 1,
            "controlled_dry_run_command_artifact_closeout_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_count", 0
            ),
            "controlled_dry_run_command_artifact_closeout_field_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_field_count", 0
            ),
            "controlled_dry_run_command_artifact_closeout_acceptance_gate_count": (
                summary.get(
                    "controlled_dry_run_command_artifact_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "runner_execution_receipt_preflight_count": summary.get(
                "runner_execution_receipt_preflight_count", 0
            ),
            "runner_execution_receipt_preflight_field_count": summary.get(
                "runner_execution_receipt_preflight_field_count", 0
            ),
            "non_executable_command_artifact_count": summary.get(
                "non_executable_command_artifact_count", 0
            ),
            "non_executable_command_artifact_field_count": summary.get(
                "non_executable_command_artifact_field_count", 0
            ),
            "execution_plan_binding_count": summary.get(
                "execution_plan_binding_count", 0
            ),
            "execution_plan_binding_field_count": summary.get(
                "execution_plan_binding_field_count", 0
            ),
            "dry_run_result_parser_count": summary.get(
                "dry_run_result_parser_count", 0
            ),
            "dry_run_result_parser_field_count": summary.get(
                "dry_run_result_parser_field_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_post_receipt_parser_verification": (
            future_database_apply_controlled_dry_run_post_receipt_parser_verification
        ),
        "controlled_dry_run_runner_execution_receipt_closeout": (
            controlled_dry_run_runner_execution_receipt_closeout
        ),
        "controlled_dry_run_runner_execution_receipt_closeout_contract": (
            controlled_dry_run_runner_execution_receipt_closeout_contract
        ),
        "controlled_dry_run_runner_execution_receipt_closeout_checks": checks,
        "source_controlled_dry_run_command_artifact_closeout_summary": summary,
        "source_controlled_dry_run_command_artifact_closeout_contract": (
            command_closeout_contract
        ),
        "source_controlled_dry_run_command_artifact_closeout": command_closeout,
        "source_database_apply_controlled_dry_run_runner_execution_receipt_preflight": (
            future_preflight
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_runner_execution_receipt_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run post-receipt parser closeout.",
            "Keep parser verification preview-only until a dedicated execution lane is explicit.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the post-receipt parser and bind no-apply enforcement."""
    runner_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_parser = (
        runner_closeout_result.get(
            "future_database_apply_controlled_dry_run_post_receipt_parser_verification"
        )
        or {}
    )
    runner_closeout = (
        runner_closeout_result.get(
            "controlled_dry_run_runner_execution_receipt_closeout"
        )
        or {}
    )
    runner_contract = (
        runner_closeout_result.get(
            "controlled_dry_run_runner_execution_receipt_closeout_contract"
        )
        or {}
    )
    summary = runner_closeout_result.get("summary") or {}
    safety = runner_closeout_result.get("safety") or {}
    parser = runner_closeout.get("post_receipt_parser_verification") or {}
    preview = runner_closeout.get("receipt_closeout_preview") or {}
    preflight = runner_closeout.get("runner_execution_receipt_preflight") or {}
    artifact = runner_closeout.get("non_executable_command_artifact") or {}
    result_parser = runner_closeout.get("dry_run_result_parser") or {}
    validation = runner_closeout.get("receipt_validation_report") or {}
    rollback_binding = runner_closeout.get("rollback_binding") or {}
    verifier_binding = runner_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_post_receipt_parser_closeout_id(
        runner_closeout_result
    )
    no_apply_enforcement_verification_id = (
        f"{closeout_id}-no-apply-enforcement-verification"
    )
    post_receipt_parser_closeout_fields = [
        "post_receipt_parser_closeout_id",
        "source_runner_execution_receipt_closeout_id",
        "source_post_receipt_parser_verification_id",
        "source_command_artifact_closeout_id",
        "source_non_executable_command_artifact_id",
        "source_receipt_closeout_preview_status",
        "dry_run_command_shape_hash",
        "no_apply_enforcement_verification_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "abort_conditions",
    ]
    post_receipt_parser_closeout_acceptance_gates = [
        "runner_execution_receipt_closeout_ready",
        "source_chain_ids_match",
        "post_receipt_parser_verification_ready",
        "post_receipt_parser_blocks_execution",
        "receipt_closeout_preview_not_executed",
        "no_apply_enforcement_verification_bound",
        "no_apply_enforcement_blocks_endpoint_sql_db_write",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    no_apply_enforcement_verification_fields = [
        "verification_id",
        "source_post_receipt_parser_verification_id",
        "source_runner_execution_receipt_closeout_id",
        "required_parser_status",
        "required_receipt_status",
        "required_command_shape_hash",
        "expected_execution_performed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_write_allowed",
        "database_apply_authorized",
        "enforcement_status",
    ]
    abort_conditions = [
        "abort_if_runner_execution_receipt_closeout_not_ready",
        "abort_if_post_receipt_parser_verification_missing",
        "abort_if_parser_verification_requires_execution",
        "abort_if_receipt_closeout_was_executed",
        "abort_if_receipt_closeout_includes_stdout_or_stderr",
        "abort_if_no_apply_enforcement_allows_endpoint_or_sql",
        "abort_if_no_apply_enforcement_allows_database_write_or_apply",
        "abort_if_command_shape_hash_mismatch",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    no_apply_enforcement_verification = {
        "verification_id": no_apply_enforcement_verification_id,
        "source_post_receipt_parser_closeout_id": closeout_id,
        "source_post_receipt_parser_verification_id": parser.get("verification_id"),
        "source_runner_execution_receipt_closeout_id": runner_closeout.get(
            "runner_execution_receipt_closeout_id"
        ),
        "source_command_artifact_closeout_id": runner_closeout.get(
            "source_command_artifact_closeout_id"
        ),
        "required_parser_status": "post_receipt_parser_preview_ready",
        "required_receipt_status": "receipt_closeout_preview_not_executed",
        "required_command_shape_hash": parser.get("required_command_shape_hash"),
        "expected_execution_performed": False,
        "expected_stdout_included": False,
        "expected_stderr_included": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "enforcement_status": "no_apply_enforcement_preview_ready",
        "no_apply_enforcement_verification_field_count": len(
            no_apply_enforcement_verification_fields
        ),
        "no_apply_enforcement_verification_fields": (
            no_apply_enforcement_verification_fields
        ),
    }
    runner_closeout_ready = (
        runner_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT_READY"
        and summary.get("controlled_dry_run_runner_execution_receipt_closeout_ready_count")
        == 1
        and summary.get("controlled_dry_run_runner_execution_receipt_closeout_pass_count")
        == summary.get("controlled_dry_run_runner_execution_receipt_closeout_check_count")
    )
    source_chain_ids_match = (
        bool(runner_closeout.get("runner_execution_receipt_closeout_id"))
        and runner_closeout.get("runner_execution_receipt_closeout_id")
        == future_parser.get("runner_execution_receipt_closeout_id")
        == no_apply_enforcement_verification.get(
            "source_runner_execution_receipt_closeout_id"
        )
        and parser.get("verification_id")
        == future_parser.get("post_receipt_parser_verification_id")
        == no_apply_enforcement_verification.get(
            "source_post_receipt_parser_verification_id"
        )
        and artifact.get("artifact_id")
        == runner_closeout.get("source_non_executable_command_artifact_id")
    )
    post_receipt_parser_verification_ready = (
        parser.get("parser_verification_status") == "post_receipt_parser_preview_ready"
        and parser.get("expected_preflight_status") == "preflight_only_not_executed"
        and parser.get("expected_receipt_status")
        == "receipt_closeout_preview_not_executed"
        and parser.get("verification_id")
        == future_parser.get("post_receipt_parser_verification_id")
        and int(parser.get("post_receipt_parser_verification_field_count") or 0)
        == 10
    )
    post_receipt_parser_blocks_execution = (
        parser.get("expected_execution_performed") is False
        and parser.get("expected_stdout_included") is False
        and parser.get("expected_stderr_included") is False
        and parser.get("execution_required") is False
        and parser.get("stdout_allowed") is False
        and parser.get("stderr_allowed") is False
        and parser.get("database_apply_authorized") is False
        and no_apply_enforcement_verification.get("expected_execution_performed")
        is False
    )
    receipt_closeout_preview_not_executed = (
        preview.get("receipt_status") == "receipt_closeout_preview_not_executed"
        and preview.get("execution_required") is False
        and preview.get("execution_performed") is False
        and preview.get("stdout_included") is False
        and preview.get("stderr_included") is False
        and preview.get("stdout_capture_allowed") is False
        and preview.get("stderr_capture_allowed") is False
        and preview.get("database_apply_authorized") is False
        and preview.get("writes_database") is False
        and preview.get("executes_endpoint") is False
        and preview.get("executes_sql") is False
    )
    no_apply_enforcement_verification_bound = (
        bool(no_apply_enforcement_verification.get("verification_id"))
        and no_apply_enforcement_verification.get(
            "source_post_receipt_parser_closeout_id"
        )
        == closeout_id
        and no_apply_enforcement_verification.get(
            "source_post_receipt_parser_verification_id"
        )
        == parser.get("verification_id")
        and no_apply_enforcement_verification.get("required_command_shape_hash")
        == parser.get("required_command_shape_hash")
        and int(
            no_apply_enforcement_verification.get(
                "no_apply_enforcement_verification_field_count"
            )
            or 0
        )
        == len(no_apply_enforcement_verification_fields)
    )
    no_apply_enforcement_blocks_endpoint_sql_db_write = (
        no_apply_enforcement_verification.get("endpoint_execution_allowed") is False
        and no_apply_enforcement_verification.get("sql_execution_allowed") is False
        and no_apply_enforcement_verification.get("database_write_allowed") is False
        and no_apply_enforcement_verification.get("database_apply_authorized")
        is False
        and no_apply_enforcement_verification.get("executes_endpoint") is False
        and no_apply_enforcement_verification.get("executes_sql") is False
        and no_apply_enforcement_verification.get("writes_database") is False
        and no_apply_enforcement_verification.get("executes_database_apply")
        is False
    )
    result_parser_and_validation_carried_forward = (
        result_parser.get("required_command_shape_hash")
        == parser.get("required_command_shape_hash")
        and result_parser.get("execution_required") is False
        and result_parser.get("stdout_allowed") is False
        and result_parser.get("stderr_allowed") is False
        and result_parser.get("database_apply_authorized") is False
        and validation.get("receipt_validation_status")
        == "preview_validated_not_executed"
        and validation.get("execution_performed") is False
        and validation.get("stdout_included") is False
        and validation.get("stderr_included") is False
        and validation.get("database_apply_authorized") is False
        and validation.get("executes_endpoint") is False
        and validation.get("executes_sql") is False
        and validation.get("writes_database") is False
    )
    target_hash_locked = (
        runner_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(runner_closeout.get("expected_sha256"))
        and bool(runner_closeout.get("actual_sha256"))
        and runner_closeout.get("expected_sha256")
        == runner_closeout.get("actual_sha256")
        and runner_closeout.get("hash_matches") is True
        and runner_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    runner_contract_blocks_database_apply = (
        runner_contract.get("executes_database_apply") is False
        and runner_contract.get("executes_endpoint") is False
        and runner_contract.get("executes_sql") is False
        and runner_contract.get("database_apply_authorized") is False
        and runner_contract.get("ready_for_database_apply_now") is False
        and runner_contract.get("signs_database_apply_authorization") is False
        and runner_contract.get("writes_database") is False
        and runner_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and no_apply_enforcement_blocks_endpoint_sql_db_write
    )
    checks = [
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "runner_execution_receipt_closeout_ready",
            runner_closeout_ready,
            {
                "result": runner_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_check_count"
                ),
            },
            "wait_for_runner_execution_receipt_closeout_ready",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "runner_execution_receipt_closeout_id": runner_closeout.get(
                    "runner_execution_receipt_closeout_id"
                ),
                "post_receipt_parser_verification_id": parser.get(
                    "verification_id"
                ),
                "artifact_id": artifact.get("artifact_id"),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "post_receipt_parser_verification_ready",
            post_receipt_parser_verification_ready,
            {
                "parser_verification_status": parser.get(
                    "parser_verification_status"
                ),
                "verification_id": parser.get("verification_id"),
                "field_count": parser.get(
                    "post_receipt_parser_verification_field_count"
                ),
            },
            "wait_for_post_receipt_parser_verification_ready",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "post_receipt_parser_blocks_execution",
            post_receipt_parser_blocks_execution,
            {
                "expected_execution_performed": parser.get(
                    "expected_execution_performed"
                ),
                "execution_required": parser.get("execution_required"),
                "database_apply_authorized": parser.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_post_receipt_parser_allows_execution",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "receipt_closeout_preview_not_executed",
            receipt_closeout_preview_not_executed,
            {
                "receipt_status": preview.get("receipt_status"),
                "execution_performed": preview.get("execution_performed"),
                "stdout_included": preview.get("stdout_included"),
                "stderr_included": preview.get("stderr_included"),
            },
            "abort_if_receipt_closeout_was_executed",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "no_apply_enforcement_verification_bound",
            no_apply_enforcement_verification_bound,
            {
                "verification_id": no_apply_enforcement_verification.get(
                    "verification_id"
                ),
                "source_post_receipt_parser_verification_id": (
                    no_apply_enforcement_verification.get(
                        "source_post_receipt_parser_verification_id"
                    )
                ),
                "field_count": no_apply_enforcement_verification.get(
                    "no_apply_enforcement_verification_field_count"
                ),
            },
            "wait_for_no_apply_enforcement_verification_binding",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "no_apply_enforcement_blocks_endpoint_sql_db_write",
            no_apply_enforcement_blocks_endpoint_sql_db_write,
            {
                "endpoint_execution_allowed": no_apply_enforcement_verification.get(
                    "endpoint_execution_allowed"
                ),
                "sql_execution_allowed": no_apply_enforcement_verification.get(
                    "sql_execution_allowed"
                ),
                "database_write_allowed": no_apply_enforcement_verification.get(
                    "database_write_allowed"
                ),
                "database_apply_authorized": no_apply_enforcement_verification.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_no_apply_enforcement_allows_endpoint_sql_or_db_write",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "result_parser_and_receipt_validation_carried_forward",
            result_parser_and_validation_carried_forward,
            {
                "parser_id": result_parser.get("parser_id"),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
                "dry_run_command_shape_hash": parser.get(
                    "required_command_shape_hash"
                ),
            },
            "wait_for_result_parser_and_receipt_validation_carry_forward",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": runner_closeout.get("target_file"),
                "hash_matches": runner_closeout.get("hash_matches"),
                "expected_sha256_present": bool(runner_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(runner_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "runner_execution_receipt_contract_blocks_database_apply",
            runner_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_post_receipt_parser_verification": (
                    runner_contract.get(
                        "permits_future_database_apply_controlled_dry_run_post_receipt_parser_verification"
                    )
                ),
                "database_apply_authorized": runner_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": runner_contract.get("writes_database"),
            },
            "abort_if_runner_execution_receipt_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_post_receipt_parser_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_no_apply_enforcement_verification = {
        "post_receipt_parser_closeout_id": closeout_id,
        "no_apply_enforcement_verification_id": no_apply_enforcement_verification_id,
        "source_runner_execution_receipt_closeout_id": runner_closeout.get(
            "runner_execution_receipt_closeout_id"
        ),
        "source_post_receipt_parser_verification_id": parser.get("verification_id"),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_apply_enforcement_verification": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_no_apply_enforcement_closeout": (
            closeout_ready
        ),
        "post_receipt_parser_closeout_ready": closeout_ready,
        "no_apply_enforcement_verification_bound": closeout_ready,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_post_receipt_parser_closeout = {
        "post_receipt_parser_closeout_id": closeout_id,
        "authorization_material_type": "controlled_dry_run_post_receipt_parser_closeout",
        "source_runner_execution_receipt_closeout_id": runner_closeout.get(
            "runner_execution_receipt_closeout_id"
        ),
        "source_post_receipt_parser_verification_id": parser.get("verification_id"),
        "source_command_artifact_closeout_id": runner_closeout.get(
            "source_command_artifact_closeout_id"
        ),
        "source_non_executable_command_artifact_id": artifact.get("artifact_id"),
        "source_receipt_closeout_preview_status": preview.get("receipt_status"),
        "dry_run_command_shape_hash": parser.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_post_receipt_parser_closeout": (
            closeout_ready
        ),
        "post_receipt_parser_closeout_fields": post_receipt_parser_closeout_fields,
        "post_receipt_parser_closeout_field_count": len(
            post_receipt_parser_closeout_fields
        ),
        "post_receipt_parser_closeout_acceptance_gates": (
            post_receipt_parser_closeout_acceptance_gates
        ),
        "post_receipt_parser_closeout_acceptance_gate_count": len(
            post_receipt_parser_closeout_acceptance_gates
        ),
        "post_receipt_parser_verification": parser,
        "post_receipt_parser_verification_count": 1,
        "receipt_closeout_preview": preview,
        "receipt_closeout_preview_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement_verification,
        "no_apply_enforcement_verification_count": 1,
        "no_apply_enforcement_verification_field_count": len(
            no_apply_enforcement_verification_fields
        ),
        "runner_execution_receipt_preflight": preflight,
        "runner_execution_receipt_preflight_count": 1,
        "runner_execution_receipt_closeout": runner_closeout,
        "runner_execution_receipt_closeout_count": 1,
        "non_executable_command_artifact": artifact,
        "non_executable_command_artifact_count": 1,
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "target_file": runner_closeout.get("target_file"),
        "expected_sha256": runner_closeout.get("expected_sha256"),
        "actual_sha256": runner_closeout.get("actual_sha256"),
        "hash_matches": runner_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "post_receipt_parser_closeout_only": True,
        "no_apply_enforcement_verification_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_post_receipt_parser_closeout_contract = {
        "mode": "controlled_dry_run_post_receipt_parser_closeout_and_no_apply_enforcement_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-post-receipt-parser-closeout"
        ),
        "source_runner_execution_receipt_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-runner-execution-receipt-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_no_apply_enforcement_verification": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(runner_closeout_result.get("success")),
        "generated_at": runner_closeout_result.get("generated_at"),
        "source_policy": runner_closeout_result.get("policy"),
        "stats": runner_closeout_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_post_receipt_parser_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_post_receipt_parser_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_post_receipt_parser_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_post_receipt_parser_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_ready_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_check_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_check_count",
                    0,
                )
            ),
            "controlled_dry_run_command_artifact_closeout_ready_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_ready_count", 0
            ),
            "controlled_dry_run_command_artifact_closeout_check_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_check_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_ready_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_ready_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_check_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_check_count", 0
            ),
            "controlled_dry_run_runner_readiness_ready_count": summary.get(
                "controlled_dry_run_runner_readiness_ready_count", 0
            ),
            "controlled_dry_run_runner_readiness_check_count": summary.get(
                "controlled_dry_run_runner_readiness_check_count", 0
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_post_receipt_parser_closeout_count": 1,
            "controlled_dry_run_post_receipt_parser_closeout_field_count": len(
                post_receipt_parser_closeout_fields
            ),
            "controlled_dry_run_post_receipt_parser_closeout_acceptance_gate_count": len(
                post_receipt_parser_closeout_acceptance_gates
            ),
            "no_apply_enforcement_verification_count": 1,
            "no_apply_enforcement_verification_field_count": len(
                no_apply_enforcement_verification_fields
            ),
            "post_receipt_parser_verification_count": summary.get(
                "post_receipt_parser_verification_count", 0
            ),
            "post_receipt_parser_verification_field_count": summary.get(
                "post_receipt_parser_verification_field_count", 0
            ),
            "receipt_closeout_preview_count": summary.get(
                "receipt_closeout_preview_count", 0
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_count": summary.get(
                "controlled_dry_run_runner_execution_receipt_closeout_count", 0
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_field_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_field_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_acceptance_gate_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "runner_execution_receipt_preflight_count": summary.get(
                "runner_execution_receipt_preflight_count", 0
            ),
            "runner_execution_receipt_preflight_field_count": summary.get(
                "runner_execution_receipt_preflight_field_count", 0
            ),
            "non_executable_command_artifact_count": summary.get(
                "non_executable_command_artifact_count", 0
            ),
            "non_executable_command_artifact_field_count": summary.get(
                "non_executable_command_artifact_field_count", 0
            ),
            "dry_run_result_parser_count": summary.get(
                "dry_run_result_parser_count", 0
            ),
            "dry_run_result_parser_field_count": summary.get(
                "dry_run_result_parser_field_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_no_apply_enforcement_verification": (
            future_database_apply_controlled_dry_run_no_apply_enforcement_verification
        ),
        "controlled_dry_run_post_receipt_parser_closeout": (
            controlled_dry_run_post_receipt_parser_closeout
        ),
        "controlled_dry_run_post_receipt_parser_closeout_contract": (
            controlled_dry_run_post_receipt_parser_closeout_contract
        ),
        "controlled_dry_run_post_receipt_parser_closeout_checks": checks,
        "source_controlled_dry_run_runner_execution_receipt_closeout_summary": summary,
        "source_controlled_dry_run_runner_execution_receipt_closeout_contract": (
            runner_contract
        ),
        "source_controlled_dry_run_runner_execution_receipt_closeout": (
            runner_closeout
        ),
        "source_database_apply_controlled_dry_run_post_receipt_parser_verification": (
            future_parser
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_post_receipt_parser_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run no-apply enforcement closeout.",
            "Keep no-apply enforcement machine-verifiable and exception-only; do not introduce manual review as the default path.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out no-apply enforcement and bind the final dry-run executor guard."""
    parser_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_enforcement = (
        parser_closeout_result.get(
            "future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
        )
        or {}
    )
    parser_closeout = (
        parser_closeout_result.get("controlled_dry_run_post_receipt_parser_closeout")
        or {}
    )
    parser_closeout_contract = (
        parser_closeout_result.get(
            "controlled_dry_run_post_receipt_parser_closeout_contract"
        )
        or {}
    )
    summary = parser_closeout_result.get("summary") or {}
    safety = parser_closeout_result.get("safety") or {}
    no_apply_enforcement = (
        parser_closeout.get("no_apply_enforcement_verification") or {}
    )
    parser = parser_closeout.get("post_receipt_parser_verification") or {}
    preview = parser_closeout.get("receipt_closeout_preview") or {}
    result_parser = parser_closeout.get("dry_run_result_parser") or {}
    validation = parser_closeout.get("receipt_validation_report") or {}
    rollback_binding = parser_closeout.get("rollback_binding") or {}
    verifier_binding = parser_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_no_apply_enforcement_closeout_id(
        parser_closeout_result
    )
    final_guard_id = f"{closeout_id}-final-dry-run-executor-guard"
    no_apply_enforcement_closeout_fields = [
        "no_apply_enforcement_closeout_id",
        "source_post_receipt_parser_closeout_id",
        "source_no_apply_enforcement_verification_id",
        "source_runner_execution_receipt_closeout_id",
        "source_command_artifact_closeout_id",
        "dry_run_command_shape_hash",
        "final_dry_run_executor_guard_id",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_write_allowed",
        "target_migration_file",
        "abort_conditions",
    ]
    no_apply_enforcement_closeout_acceptance_gates = [
        "post_receipt_parser_closeout_ready",
        "source_chain_ids_match",
        "no_apply_enforcement_verification_ready",
        "no_apply_blocks_endpoint_sql_db_write",
        "final_dry_run_executor_guard_bound",
        "final_executor_guard_blocks_execution",
        "parser_and_receipt_preview_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    final_dry_run_executor_guard_fields = [
        "guard_id",
        "source_no_apply_enforcement_closeout_id",
        "source_no_apply_enforcement_verification_id",
        "required_enforcement_status",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_write_allowed",
        "dry_run_executor_invocation_allowed",
        "stdout_capture_allowed",
        "stderr_capture_allowed",
        "database_apply_authorized",
        "guard_status",
    ]
    abort_conditions = [
        "abort_if_post_receipt_parser_closeout_not_ready",
        "abort_if_no_apply_enforcement_verification_missing",
        "abort_if_no_apply_enforcement_allows_endpoint_execution",
        "abort_if_no_apply_enforcement_allows_sql_execution",
        "abort_if_no_apply_enforcement_allows_database_write",
        "abort_if_final_dry_run_executor_guard_allows_invocation",
        "abort_if_stdout_or_stderr_capture_is_allowed",
        "abort_if_database_apply_authorization_is_present",
        "abort_if_command_shape_hash_mismatch",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    final_dry_run_executor_guard = {
        "guard_id": final_guard_id,
        "source_no_apply_enforcement_closeout_id": closeout_id,
        "source_post_receipt_parser_closeout_id": parser_closeout.get(
            "post_receipt_parser_closeout_id"
        ),
        "source_no_apply_enforcement_verification_id": no_apply_enforcement.get(
            "verification_id"
        ),
        "source_runner_execution_receipt_closeout_id": parser_closeout.get(
            "source_runner_execution_receipt_closeout_id"
        ),
        "source_command_artifact_closeout_id": parser_closeout.get(
            "source_command_artifact_closeout_id"
        ),
        "required_enforcement_status": "no_apply_enforcement_preview_ready",
        "required_command_shape_hash": parser_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "guard_status": "final_dry_run_executor_guard_preview_ready",
        "final_dry_run_executor_guard_field_count": len(
            final_dry_run_executor_guard_fields
        ),
        "final_dry_run_executor_guard_fields": final_dry_run_executor_guard_fields,
    }
    post_receipt_parser_closeout_ready = (
        parser_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT_READY"
        and summary.get("controlled_dry_run_post_receipt_parser_closeout_ready_count")
        == 1
        and summary.get("controlled_dry_run_post_receipt_parser_closeout_pass_count")
        == summary.get("controlled_dry_run_post_receipt_parser_closeout_check_count")
    )
    source_chain_ids_match = (
        bool(parser_closeout.get("post_receipt_parser_closeout_id"))
        and parser_closeout.get("post_receipt_parser_closeout_id")
        == future_enforcement.get("post_receipt_parser_closeout_id")
        == no_apply_enforcement.get("source_post_receipt_parser_closeout_id")
        == final_dry_run_executor_guard.get(
            "source_post_receipt_parser_closeout_id"
        )
        and no_apply_enforcement.get("verification_id")
        == future_enforcement.get("no_apply_enforcement_verification_id")
        == final_dry_run_executor_guard.get(
            "source_no_apply_enforcement_verification_id"
        )
        and parser_closeout.get("source_runner_execution_receipt_closeout_id")
        == future_enforcement.get("source_runner_execution_receipt_closeout_id")
        == final_dry_run_executor_guard.get(
            "source_runner_execution_receipt_closeout_id"
        )
    )
    no_apply_enforcement_verification_ready = (
        no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("verification_id")
        == future_enforcement.get("no_apply_enforcement_verification_id")
        and int(
            no_apply_enforcement.get(
                "no_apply_enforcement_verification_field_count"
            )
            or 0
        )
        == 12
    )
    no_apply_blocks_endpoint_sql_db_write = (
        no_apply_enforcement.get("endpoint_execution_allowed") is False
        and no_apply_enforcement.get("sql_execution_allowed") is False
        and no_apply_enforcement.get("database_write_allowed") is False
        and no_apply_enforcement.get("database_apply_authorized") is False
        and no_apply_enforcement.get("executes_endpoint") is False
        and no_apply_enforcement.get("executes_sql") is False
        and no_apply_enforcement.get("writes_database") is False
        and no_apply_enforcement.get("executes_database_apply") is False
        and future_enforcement.get("endpoint_execution_allowed") is False
        and future_enforcement.get("sql_execution_allowed") is False
        and future_enforcement.get("database_write_allowed") is False
    )
    final_dry_run_executor_guard_bound = (
        bool(final_dry_run_executor_guard.get("guard_id"))
        and final_dry_run_executor_guard.get(
            "source_no_apply_enforcement_closeout_id"
        )
        == closeout_id
        and final_dry_run_executor_guard.get(
            "source_no_apply_enforcement_verification_id"
        )
        == no_apply_enforcement.get("verification_id")
        and final_dry_run_executor_guard.get("required_command_shape_hash")
        == parser_closeout.get("dry_run_command_shape_hash")
        and int(
            final_dry_run_executor_guard.get(
                "final_dry_run_executor_guard_field_count"
            )
            or 0
        )
        == len(final_dry_run_executor_guard_fields)
    )
    final_executor_guard_blocks_execution = (
        final_dry_run_executor_guard.get("endpoint_execution_allowed") is False
        and final_dry_run_executor_guard.get("sql_execution_allowed") is False
        and final_dry_run_executor_guard.get("database_write_allowed") is False
        and final_dry_run_executor_guard.get("dry_run_executor_invocation_allowed")
        is False
        and final_dry_run_executor_guard.get("stdout_capture_allowed") is False
        and final_dry_run_executor_guard.get("stderr_capture_allowed") is False
        and final_dry_run_executor_guard.get("database_apply_authorized") is False
        and final_dry_run_executor_guard.get("executes_database_apply") is False
        and final_dry_run_executor_guard.get("executes_endpoint") is False
        and final_dry_run_executor_guard.get("executes_sql") is False
        and final_dry_run_executor_guard.get("writes_database") is False
    )
    parser_and_receipt_preview_carried_forward = (
        parser.get("parser_verification_status") == "post_receipt_parser_preview_ready"
        and parser.get("expected_execution_performed") is False
        and parser.get("expected_stdout_included") is False
        and parser.get("expected_stderr_included") is False
        and parser.get("database_apply_authorized") is False
        and preview.get("receipt_status") == "receipt_closeout_preview_not_executed"
        and preview.get("execution_performed") is False
        and preview.get("stdout_included") is False
        and preview.get("stderr_included") is False
        and preview.get("writes_database") is False
        and result_parser.get("required_command_shape_hash")
        == parser_closeout.get("dry_run_command_shape_hash")
        and result_parser.get("database_apply_authorized") is False
        and validation.get("receipt_validation_status")
        == "preview_validated_not_executed"
        and validation.get("writes_database") is False
    )
    target_hash_locked = (
        parser_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(parser_closeout.get("expected_sha256"))
        and bool(parser_closeout.get("actual_sha256"))
        and parser_closeout.get("expected_sha256")
        == parser_closeout.get("actual_sha256")
        and parser_closeout.get("hash_matches") is True
        and parser_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    parser_closeout_contract_blocks_database_apply = (
        parser_closeout_contract.get("executes_database_apply") is False
        and parser_closeout_contract.get("executes_endpoint") is False
        and parser_closeout_contract.get("executes_sql") is False
        and parser_closeout_contract.get("database_apply_authorized") is False
        and parser_closeout_contract.get("ready_for_database_apply_now") is False
        and parser_closeout_contract.get("signs_database_apply_authorization")
        is False
        and parser_closeout_contract.get("writes_database") is False
        and parser_closeout_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and no_apply_blocks_endpoint_sql_db_write
        and final_executor_guard_blocks_execution
    )
    checks = [
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "post_receipt_parser_closeout_ready",
            post_receipt_parser_closeout_ready,
            {
                "result": parser_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_check_count"
                ),
            },
            "wait_for_post_receipt_parser_closeout_ready",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "post_receipt_parser_closeout_id": parser_closeout.get(
                    "post_receipt_parser_closeout_id"
                ),
                "no_apply_enforcement_verification_id": no_apply_enforcement.get(
                    "verification_id"
                ),
                "runner_execution_receipt_closeout_id": parser_closeout.get(
                    "source_runner_execution_receipt_closeout_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "no_apply_enforcement_verification_ready",
            no_apply_enforcement_verification_ready,
            {
                "enforcement_status": no_apply_enforcement.get(
                    "enforcement_status"
                ),
                "verification_id": no_apply_enforcement.get("verification_id"),
                "field_count": no_apply_enforcement.get(
                    "no_apply_enforcement_verification_field_count"
                ),
            },
            "wait_for_no_apply_enforcement_verification_ready",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "no_apply_blocks_endpoint_sql_db_write",
            no_apply_blocks_endpoint_sql_db_write,
            {
                "endpoint_execution_allowed": no_apply_enforcement.get(
                    "endpoint_execution_allowed"
                ),
                "sql_execution_allowed": no_apply_enforcement.get(
                    "sql_execution_allowed"
                ),
                "database_write_allowed": no_apply_enforcement.get(
                    "database_write_allowed"
                ),
                "database_apply_authorized": no_apply_enforcement.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_no_apply_enforcement_allows_endpoint_sql_or_db_write",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "final_dry_run_executor_guard_bound",
            final_dry_run_executor_guard_bound,
            {
                "guard_id": final_dry_run_executor_guard.get("guard_id"),
                "source_no_apply_enforcement_verification_id": (
                    final_dry_run_executor_guard.get(
                        "source_no_apply_enforcement_verification_id"
                    )
                ),
                "field_count": final_dry_run_executor_guard.get(
                    "final_dry_run_executor_guard_field_count"
                ),
            },
            "wait_for_final_dry_run_executor_guard_binding",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "final_executor_guard_blocks_execution",
            final_executor_guard_blocks_execution,
            {
                "dry_run_executor_invocation_allowed": (
                    final_dry_run_executor_guard.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "endpoint_execution_allowed": final_dry_run_executor_guard.get(
                    "endpoint_execution_allowed"
                ),
                "sql_execution_allowed": final_dry_run_executor_guard.get(
                    "sql_execution_allowed"
                ),
                "database_write_allowed": final_dry_run_executor_guard.get(
                    "database_write_allowed"
                ),
            },
            "abort_if_final_executor_guard_allows_execution",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "parser_and_receipt_preview_carried_forward",
            parser_and_receipt_preview_carried_forward,
            {
                "parser_verification_status": parser.get(
                    "parser_verification_status"
                ),
                "receipt_status": preview.get("receipt_status"),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
            },
            "wait_for_parser_and_receipt_preview_carry_forward",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": parser_closeout.get("target_file"),
                "hash_matches": parser_closeout.get("hash_matches"),
                "expected_sha256_present": bool(parser_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(parser_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "post_receipt_parser_contract_blocks_database_apply",
            parser_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_no_apply_enforcement_verification": (
                    parser_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
                    )
                ),
                "database_apply_authorized": parser_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": parser_closeout_contract.get("writes_database"),
            },
            "abort_if_post_receipt_parser_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_no_apply_enforcement_closeout_check(
            "manual_review_not_required_for_safe_preview",
            parser_closeout_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": parser_closeout_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_final_dry_run_executor_guard = {
        "no_apply_enforcement_closeout_id": closeout_id,
        "final_dry_run_executor_guard_id": final_guard_id,
        "source_post_receipt_parser_closeout_id": parser_closeout.get(
            "post_receipt_parser_closeout_id"
        ),
        "source_no_apply_enforcement_verification_id": no_apply_enforcement.get(
            "verification_id"
        ),
        "source_runner_execution_receipt_closeout_id": parser_closeout.get(
            "source_runner_execution_receipt_closeout_id"
        ),
        "source_non_executable_command_artifact_id": parser_closeout.get(
            "source_non_executable_command_artifact_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_final_dry_run_executor_guard": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_final_executor_guard_closeout": (
            closeout_ready
        ),
        "no_apply_enforcement_closeout_ready": closeout_ready,
        "final_dry_run_executor_guard_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_no_apply_enforcement_closeout = {
        "no_apply_enforcement_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_no_apply_enforcement_closeout"
        ),
        "source_post_receipt_parser_closeout_id": parser_closeout.get(
            "post_receipt_parser_closeout_id"
        ),
        "source_no_apply_enforcement_verification_id": no_apply_enforcement.get(
            "verification_id"
        ),
        "source_runner_execution_receipt_closeout_id": parser_closeout.get(
            "source_runner_execution_receipt_closeout_id"
        ),
        "source_command_artifact_closeout_id": parser_closeout.get(
            "source_command_artifact_closeout_id"
        ),
        "source_non_executable_command_artifact_id": parser_closeout.get(
            "source_non_executable_command_artifact_id"
        ),
        "dry_run_command_shape_hash": parser_closeout.get(
            "dry_run_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_apply_enforcement_closeout": (
            closeout_ready
        ),
        "no_apply_enforcement_closeout_fields": no_apply_enforcement_closeout_fields,
        "no_apply_enforcement_closeout_field_count": len(
            no_apply_enforcement_closeout_fields
        ),
        "no_apply_enforcement_closeout_acceptance_gates": (
            no_apply_enforcement_closeout_acceptance_gates
        ),
        "no_apply_enforcement_closeout_acceptance_gate_count": len(
            no_apply_enforcement_closeout_acceptance_gates
        ),
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "final_dry_run_executor_guard": final_dry_run_executor_guard,
        "final_dry_run_executor_guard_count": 1,
        "final_dry_run_executor_guard_field_count": len(
            final_dry_run_executor_guard_fields
        ),
        "post_receipt_parser_closeout": parser_closeout,
        "post_receipt_parser_closeout_count": 1,
        "post_receipt_parser_verification": parser,
        "post_receipt_parser_verification_count": 1,
        "receipt_closeout_preview": preview,
        "receipt_closeout_preview_count": 1,
        "dry_run_result_parser": result_parser,
        "dry_run_result_parser_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "target_file": parser_closeout.get("target_file"),
        "expected_sha256": parser_closeout.get("expected_sha256"),
        "actual_sha256": parser_closeout.get("actual_sha256"),
        "hash_matches": parser_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "no_apply_enforcement_closeout_only": True,
        "final_dry_run_executor_guard_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_no_apply_enforcement_closeout_contract = {
        "mode": "controlled_dry_run_no_apply_enforcement_closeout_and_final_executor_guard_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-apply-enforcement-closeout"
        ),
        "source_post_receipt_parser_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-post-receipt-parser-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_final_dry_run_executor_guard": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(parser_closeout_result.get("success")),
        "generated_at": parser_closeout_result.get("generated_at"),
        "source_policy": parser_closeout_result.get("policy"),
        "stats": parser_closeout_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_no_apply_enforcement_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_post_receipt_parser_closeout_ready_count": (
                summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_post_receipt_parser_closeout_check_count": (
                summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_check_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_ready_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_check_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_check_count",
                    0,
                )
            ),
            "controlled_dry_run_command_artifact_closeout_ready_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_ready_count", 0
            ),
            "controlled_dry_run_command_artifact_closeout_check_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_check_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_ready_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_ready_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_check_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_check_count", 0
            ),
            "controlled_dry_run_runner_readiness_ready_count": summary.get(
                "controlled_dry_run_runner_readiness_ready_count", 0
            ),
            "controlled_dry_run_runner_readiness_check_count": summary.get(
                "controlled_dry_run_runner_readiness_check_count", 0
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_count": 1,
            "controlled_dry_run_no_apply_enforcement_closeout_field_count": len(
                no_apply_enforcement_closeout_fields
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_acceptance_gate_count": len(
                no_apply_enforcement_closeout_acceptance_gates
            ),
            "final_dry_run_executor_guard_count": 1,
            "final_dry_run_executor_guard_field_count": len(
                final_dry_run_executor_guard_fields
            ),
            "controlled_dry_run_post_receipt_parser_closeout_count": summary.get(
                "controlled_dry_run_post_receipt_parser_closeout_count", 0
            ),
            "controlled_dry_run_post_receipt_parser_closeout_field_count": (
                summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_field_count",
                    0,
                )
            ),
            "controlled_dry_run_post_receipt_parser_closeout_acceptance_gate_count": (
                summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "no_apply_enforcement_verification_count": summary.get(
                "no_apply_enforcement_verification_count", 0
            ),
            "no_apply_enforcement_verification_field_count": summary.get(
                "no_apply_enforcement_verification_field_count", 0
            ),
            "post_receipt_parser_verification_count": summary.get(
                "post_receipt_parser_verification_count", 0
            ),
            "post_receipt_parser_verification_field_count": summary.get(
                "post_receipt_parser_verification_field_count", 0
            ),
            "receipt_closeout_preview_count": summary.get(
                "receipt_closeout_preview_count", 0
            ),
            "runner_execution_receipt_preflight_count": summary.get(
                "runner_execution_receipt_preflight_count", 0
            ),
            "runner_execution_receipt_preflight_field_count": summary.get(
                "runner_execution_receipt_preflight_field_count", 0
            ),
            "non_executable_command_artifact_count": summary.get(
                "non_executable_command_artifact_count", 0
            ),
            "non_executable_command_artifact_field_count": summary.get(
                "non_executable_command_artifact_field_count", 0
            ),
            "dry_run_result_parser_count": summary.get(
                "dry_run_result_parser_count", 0
            ),
            "dry_run_result_parser_field_count": summary.get(
                "dry_run_result_parser_field_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_final_dry_run_executor_guard": (
            future_database_apply_controlled_dry_run_final_dry_run_executor_guard
        ),
        "controlled_dry_run_no_apply_enforcement_closeout": (
            controlled_dry_run_no_apply_enforcement_closeout
        ),
        "controlled_dry_run_no_apply_enforcement_closeout_contract": (
            controlled_dry_run_no_apply_enforcement_closeout_contract
        ),
        "controlled_dry_run_no_apply_enforcement_closeout_checks": checks,
        "source_controlled_dry_run_post_receipt_parser_closeout_summary": summary,
        "source_controlled_dry_run_post_receipt_parser_closeout_contract": (
            parser_closeout_contract
        ),
        "source_controlled_dry_run_post_receipt_parser_closeout": parser_closeout,
        "source_database_apply_controlled_dry_run_no_apply_enforcement_verification": (
            future_enforcement
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_no_apply_enforcement_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run final executor guard closeout.",
            "Keep the final dry-run executor guard machine-verifiable and non-invoking until an explicit apply lane is built.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the final dry-run executor guard and bind replay verification."""
    no_apply_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_guard = (
        no_apply_closeout_result.get(
            "future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
        )
        or {}
    )
    no_apply_closeout = (
        no_apply_closeout_result.get(
            "controlled_dry_run_no_apply_enforcement_closeout"
        )
        or {}
    )
    no_apply_contract = (
        no_apply_closeout_result.get(
            "controlled_dry_run_no_apply_enforcement_closeout_contract"
        )
        or {}
    )
    summary = no_apply_closeout_result.get("summary") or {}
    safety = no_apply_closeout_result.get("safety") or {}
    final_guard = no_apply_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        no_apply_closeout.get("no_apply_enforcement_verification") or {}
    )
    parser_closeout = no_apply_closeout.get("post_receipt_parser_closeout") or {}
    parser = no_apply_closeout.get("post_receipt_parser_verification") or {}
    preview = no_apply_closeout.get("receipt_closeout_preview") or {}
    validation = no_apply_closeout.get("receipt_validation_report") or {}
    rollback_binding = no_apply_closeout.get("rollback_binding") or {}
    verifier_binding = no_apply_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_final_executor_guard_closeout_id(
        no_apply_closeout_result
    )
    replay_verifier_id = f"{closeout_id}-pre-apply-replay-verifier"
    final_executor_guard_closeout_fields = [
        "final_executor_guard_closeout_id",
        "source_no_apply_enforcement_closeout_id",
        "source_final_dry_run_executor_guard_id",
        "source_no_apply_enforcement_verification_id",
        "source_post_receipt_parser_closeout_id",
        "dry_run_command_shape_hash",
        "pre_apply_replay_verifier_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    final_executor_guard_closeout_acceptance_gates = [
        "no_apply_enforcement_closeout_ready",
        "source_chain_ids_match",
        "final_dry_run_executor_guard_ready",
        "final_executor_guard_blocks_invocation",
        "pre_apply_replay_verifier_bound",
        "pre_apply_replay_verifier_preview_only",
        "no_apply_enforcement_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    pre_apply_replay_verifier_fields = [
        "verification_id",
        "source_final_executor_guard_closeout_id",
        "source_final_dry_run_executor_guard_id",
        "source_no_apply_enforcement_closeout_id",
        "required_guard_status",
        "required_enforcement_status",
        "required_command_shape_hash",
        "replay_mode",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_write_allowed",
    ]
    abort_conditions = [
        "abort_if_no_apply_enforcement_closeout_not_ready",
        "abort_if_final_dry_run_executor_guard_missing",
        "abort_if_final_guard_allows_invocation",
        "abort_if_replay_verifier_requests_execution",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_stdout_or_stderr_capture_is_allowed",
        "abort_if_command_shape_hash_mismatch",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    pre_apply_replay_verifier = {
        "verification_id": replay_verifier_id,
        "source_final_executor_guard_closeout_id": closeout_id,
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "source_no_apply_enforcement_closeout_id": no_apply_closeout.get(
            "no_apply_enforcement_closeout_id"
        ),
        "source_no_apply_enforcement_verification_id": no_apply_enforcement.get(
            "verification_id"
        ),
        "source_post_receipt_parser_closeout_id": parser_closeout.get(
            "post_receipt_parser_closeout_id"
        ),
        "required_guard_status": "final_dry_run_executor_guard_preview_ready",
        "required_enforcement_status": "no_apply_enforcement_preview_ready",
        "required_command_shape_hash": final_guard.get("required_command_shape_hash"),
        "replay_mode": "pre_apply_replay_preview_only",
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "verifier_status": "pre_apply_replay_verifier_preview_ready",
        "pre_apply_replay_verifier_field_count": len(
            pre_apply_replay_verifier_fields
        ),
        "pre_apply_replay_verifier_fields": pre_apply_replay_verifier_fields,
    }
    no_apply_closeout_ready = (
        no_apply_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT_READY"
        and summary.get("controlled_dry_run_no_apply_enforcement_closeout_ready_count")
        == 1
        and summary.get("controlled_dry_run_no_apply_enforcement_closeout_pass_count")
        == summary.get("controlled_dry_run_no_apply_enforcement_closeout_check_count")
    )
    source_chain_ids_match = (
        bool(no_apply_closeout.get("no_apply_enforcement_closeout_id"))
        and no_apply_closeout.get("no_apply_enforcement_closeout_id")
        == future_guard.get("no_apply_enforcement_closeout_id")
        == final_guard.get("source_no_apply_enforcement_closeout_id")
        == pre_apply_replay_verifier.get(
            "source_no_apply_enforcement_closeout_id"
        )
        and final_guard.get("guard_id")
        == future_guard.get("final_dry_run_executor_guard_id")
        == pre_apply_replay_verifier.get("source_final_dry_run_executor_guard_id")
        and no_apply_enforcement.get("verification_id")
        == no_apply_closeout.get("source_no_apply_enforcement_verification_id")
        == pre_apply_replay_verifier.get(
            "source_no_apply_enforcement_verification_id"
        )
    )
    final_dry_run_executor_guard_ready = (
        final_guard.get("guard_status") == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("guard_id")
        == future_guard.get("final_dry_run_executor_guard_id")
        and int(final_guard.get("final_dry_run_executor_guard_field_count") or 0)
        == 12
    )
    final_executor_guard_blocks_invocation = (
        final_guard.get("dry_run_executor_invocation_allowed") is False
        and final_guard.get("endpoint_execution_allowed") is False
        and final_guard.get("sql_execution_allowed") is False
        and final_guard.get("database_write_allowed") is False
        and final_guard.get("stdout_capture_allowed") is False
        and final_guard.get("stderr_capture_allowed") is False
        and final_guard.get("database_apply_authorized") is False
        and final_guard.get("executes_database_apply") is False
        and final_guard.get("executes_endpoint") is False
        and final_guard.get("executes_sql") is False
        and final_guard.get("writes_database") is False
    )
    pre_apply_replay_verifier_bound = (
        bool(pre_apply_replay_verifier.get("verification_id"))
        and pre_apply_replay_verifier.get("source_final_executor_guard_closeout_id")
        == closeout_id
        and pre_apply_replay_verifier.get("source_final_dry_run_executor_guard_id")
        == final_guard.get("guard_id")
        and pre_apply_replay_verifier.get("required_command_shape_hash")
        == final_guard.get("required_command_shape_hash")
        and int(
            pre_apply_replay_verifier.get("pre_apply_replay_verifier_field_count")
            or 0
        )
        == len(pre_apply_replay_verifier_fields)
    )
    pre_apply_replay_verifier_preview_only = (
        pre_apply_replay_verifier.get("replay_mode")
        == "pre_apply_replay_preview_only"
        and pre_apply_replay_verifier.get("dry_run_executor_invocation_allowed")
        is False
        and pre_apply_replay_verifier.get("endpoint_execution_allowed") is False
        and pre_apply_replay_verifier.get("sql_execution_allowed") is False
        and pre_apply_replay_verifier.get("database_write_allowed") is False
        and pre_apply_replay_verifier.get("stdout_capture_allowed") is False
        and pre_apply_replay_verifier.get("stderr_capture_allowed") is False
        and pre_apply_replay_verifier.get("database_apply_authorized") is False
        and pre_apply_replay_verifier.get("executes_database_apply") is False
        and pre_apply_replay_verifier.get("executes_endpoint") is False
        and pre_apply_replay_verifier.get("executes_sql") is False
        and pre_apply_replay_verifier.get("writes_database") is False
    )
    no_apply_enforcement_carried_forward = (
        no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("endpoint_execution_allowed") is False
        and no_apply_enforcement.get("sql_execution_allowed") is False
        and no_apply_enforcement.get("database_write_allowed") is False
        and no_apply_enforcement.get("database_apply_authorized") is False
        and parser.get("parser_verification_status")
        == "post_receipt_parser_preview_ready"
        and preview.get("receipt_status") == "receipt_closeout_preview_not_executed"
        and validation.get("receipt_validation_status")
        == "preview_validated_not_executed"
    )
    target_hash_locked = (
        no_apply_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(no_apply_closeout.get("expected_sha256"))
        and bool(no_apply_closeout.get("actual_sha256"))
        and no_apply_closeout.get("expected_sha256")
        == no_apply_closeout.get("actual_sha256")
        and no_apply_closeout.get("hash_matches") is True
        and no_apply_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    no_apply_contract_blocks_database_apply = (
        no_apply_contract.get("executes_database_apply") is False
        and no_apply_contract.get("executes_endpoint") is False
        and no_apply_contract.get("executes_sql") is False
        and no_apply_contract.get("database_apply_authorized") is False
        and no_apply_contract.get("ready_for_database_apply_now") is False
        and no_apply_contract.get("signs_database_apply_authorization") is False
        and no_apply_contract.get("writes_database") is False
        and no_apply_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and final_executor_guard_blocks_invocation
        and pre_apply_replay_verifier_preview_only
    )
    checks = [
        _controlled_dry_run_final_executor_guard_closeout_check(
            "no_apply_enforcement_closeout_ready",
            no_apply_closeout_ready,
            {
                "result": no_apply_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_check_count"
                ),
            },
            "wait_for_no_apply_enforcement_closeout_ready",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "no_apply_enforcement_closeout_id": no_apply_closeout.get(
                    "no_apply_enforcement_closeout_id"
                ),
                "final_guard_id": final_guard.get("guard_id"),
                "no_apply_enforcement_verification_id": no_apply_enforcement.get(
                    "verification_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "final_dry_run_executor_guard_ready",
            final_dry_run_executor_guard_ready,
            {
                "guard_status": final_guard.get("guard_status"),
                "guard_id": final_guard.get("guard_id"),
                "field_count": final_guard.get(
                    "final_dry_run_executor_guard_field_count"
                ),
            },
            "wait_for_final_dry_run_executor_guard_ready",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "final_executor_guard_blocks_invocation",
            final_executor_guard_blocks_invocation,
            {
                "dry_run_executor_invocation_allowed": final_guard.get(
                    "dry_run_executor_invocation_allowed"
                ),
                "endpoint_execution_allowed": final_guard.get(
                    "endpoint_execution_allowed"
                ),
                "sql_execution_allowed": final_guard.get("sql_execution_allowed"),
                "database_write_allowed": final_guard.get(
                    "database_write_allowed"
                ),
            },
            "abort_if_final_guard_allows_invocation",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "pre_apply_replay_verifier_bound",
            pre_apply_replay_verifier_bound,
            {
                "verification_id": pre_apply_replay_verifier.get(
                    "verification_id"
                ),
                "source_final_dry_run_executor_guard_id": (
                    pre_apply_replay_verifier.get(
                        "source_final_dry_run_executor_guard_id"
                    )
                ),
                "field_count": pre_apply_replay_verifier.get(
                    "pre_apply_replay_verifier_field_count"
                ),
            },
            "wait_for_pre_apply_replay_verifier_binding",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "pre_apply_replay_verifier_preview_only",
            pre_apply_replay_verifier_preview_only,
            {
                "replay_mode": pre_apply_replay_verifier.get("replay_mode"),
                "dry_run_executor_invocation_allowed": (
                    pre_apply_replay_verifier.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "database_apply_authorized": pre_apply_replay_verifier.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_pre_apply_replay_verifier_requests_execution",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "no_apply_enforcement_carried_forward",
            no_apply_enforcement_carried_forward,
            {
                "enforcement_status": no_apply_enforcement.get(
                    "enforcement_status"
                ),
                "parser_verification_status": parser.get(
                    "parser_verification_status"
                ),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
            },
            "wait_for_no_apply_enforcement_carry_forward",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": no_apply_closeout.get("target_file"),
                "hash_matches": no_apply_closeout.get("hash_matches"),
                "expected_sha256_present": bool(no_apply_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(no_apply_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "rollback_and_post_apply_verifier_bindings_carried_forward",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "no_apply_enforcement_contract_blocks_database_apply",
            no_apply_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_final_dry_run_executor_guard": (
                    no_apply_contract.get(
                        "permits_future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
                    )
                ),
                "database_apply_authorized": no_apply_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": no_apply_contract.get("writes_database"),
            },
            "abort_if_no_apply_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_final_executor_guard_closeout_check(
            "manual_review_not_required_for_safe_preview",
            no_apply_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": no_apply_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_pre_apply_replay_verifier = {
        "final_executor_guard_closeout_id": closeout_id,
        "pre_apply_replay_verifier_id": replay_verifier_id,
        "source_no_apply_enforcement_closeout_id": no_apply_closeout.get(
            "no_apply_enforcement_closeout_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "source_no_apply_enforcement_verification_id": no_apply_enforcement.get(
            "verification_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_pre_apply_replay_verifier": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_pre_apply_replay_closeout": (
            closeout_ready
        ),
        "final_executor_guard_closeout_ready": closeout_ready,
        "pre_apply_replay_verifier_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "stdout_capture_allowed": False,
        "stderr_capture_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_final_executor_guard_closeout = {
        "final_executor_guard_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_final_executor_guard_closeout"
        ),
        "source_no_apply_enforcement_closeout_id": no_apply_closeout.get(
            "no_apply_enforcement_closeout_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "source_no_apply_enforcement_verification_id": no_apply_enforcement.get(
            "verification_id"
        ),
        "source_post_receipt_parser_closeout_id": parser_closeout.get(
            "post_receipt_parser_closeout_id"
        ),
        "dry_run_command_shape_hash": final_guard.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_final_executor_guard_closeout": (
            closeout_ready
        ),
        "final_executor_guard_closeout_fields": final_executor_guard_closeout_fields,
        "final_executor_guard_closeout_field_count": len(
            final_executor_guard_closeout_fields
        ),
        "final_executor_guard_closeout_acceptance_gates": (
            final_executor_guard_closeout_acceptance_gates
        ),
        "final_executor_guard_closeout_acceptance_gate_count": len(
            final_executor_guard_closeout_acceptance_gates
        ),
        "pre_apply_replay_verifier": pre_apply_replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "pre_apply_replay_verifier_field_count": len(
            pre_apply_replay_verifier_fields
        ),
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "no_apply_enforcement_closeout": no_apply_closeout,
        "no_apply_enforcement_closeout_count": 1,
        "post_receipt_parser_closeout": parser_closeout,
        "post_receipt_parser_closeout_count": 1,
        "post_receipt_parser_verification": parser,
        "post_receipt_parser_verification_count": 1,
        "receipt_closeout_preview": preview,
        "receipt_closeout_preview_count": 1,
        "receipt_validation_report": validation,
        "receipt_validation_report_count": 1,
        "target_file": no_apply_closeout.get("target_file"),
        "expected_sha256": no_apply_closeout.get("expected_sha256"),
        "actual_sha256": no_apply_closeout.get("actual_sha256"),
        "hash_matches": no_apply_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "final_executor_guard_closeout_only": True,
        "pre_apply_replay_verifier_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_final_executor_guard_closeout_contract = {
        "mode": "controlled_dry_run_final_executor_guard_closeout_and_pre_apply_replay_verifier_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-final-executor-guard-closeout"
        ),
        "source_no_apply_enforcement_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-apply-enforcement-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_pre_apply_replay_verifier": (
            closeout_ready
        ),
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "ready_for_database_apply_now": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(no_apply_closeout_result.get("success")),
        "generated_at": no_apply_closeout_result.get("generated_at"),
        "source_policy": no_apply_closeout_result.get("policy"),
        "stats": no_apply_closeout_result.get("stats") or {},
        "summary": {
            "controlled_dry_run_final_executor_guard_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_final_executor_guard_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_final_executor_guard_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_final_executor_guard_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_ready_count": (
                summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_check_count": (
                summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_check_count",
                    0,
                )
            ),
            "controlled_dry_run_post_receipt_parser_closeout_ready_count": (
                summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_post_receipt_parser_closeout_check_count": (
                summary.get(
                    "controlled_dry_run_post_receipt_parser_closeout_check_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_ready_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_runner_execution_receipt_closeout_check_count": (
                summary.get(
                    "controlled_dry_run_runner_execution_receipt_closeout_check_count",
                    0,
                )
            ),
            "controlled_dry_run_command_artifact_closeout_ready_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_ready_count", 0
            ),
            "controlled_dry_run_command_artifact_closeout_check_count": summary.get(
                "controlled_dry_run_command_artifact_closeout_check_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_ready_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_ready_count", 0
            ),
            "controlled_dry_run_execution_plan_closeout_check_count": summary.get(
                "controlled_dry_run_execution_plan_closeout_check_count", 0
            ),
            "controlled_dry_run_runner_readiness_ready_count": summary.get(
                "controlled_dry_run_runner_readiness_ready_count", 0
            ),
            "controlled_dry_run_runner_readiness_check_count": summary.get(
                "controlled_dry_run_runner_readiness_check_count", 0
            ),
            "controlled_dry_run_receipt_closeout_ready_count": summary.get(
                "controlled_dry_run_receipt_closeout_ready_count", 0
            ),
            "controlled_dry_run_receipt_closeout_check_count": summary.get(
                "controlled_dry_run_receipt_closeout_check_count", 0
            ),
            "controlled_dry_run_package_ready_count": summary.get(
                "controlled_dry_run_package_ready_count", 0
            ),
            "controlled_dry_run_package_check_count": summary.get(
                "controlled_dry_run_package_check_count", 0
            ),
            "controlled_apply_final_preflight_ready_count": summary.get(
                "controlled_apply_final_preflight_ready_count", 0
            ),
            "controlled_apply_final_preflight_check_count": summary.get(
                "controlled_apply_final_preflight_check_count", 0
            ),
            "authorization_evidence_execution_closeout_ready_count": summary.get(
                "authorization_evidence_execution_closeout_ready_count", 0
            ),
            "authorization_evidence_execution_closeout_check_count": summary.get(
                "authorization_evidence_execution_closeout_check_count", 0
            ),
            "authorization_evidence_execution_preflight_ready_count": summary.get(
                "authorization_evidence_execution_preflight_ready_count", 0
            ),
            "authorization_evidence_execution_preflight_check_count": summary.get(
                "authorization_evidence_execution_preflight_check_count", 0
            ),
            "database_apply_final_verifier_gate_count": summary.get(
                "database_apply_final_verifier_gate_count", 0
            ),
            "database_apply_authorization_final_verifier_gate_ready_count": (
                summary.get(
                    "database_apply_authorization_final_verifier_gate_ready_count",
                    0,
                )
            ),
            "controlled_dry_run_final_executor_guard_closeout_count": 1,
            "controlled_dry_run_final_executor_guard_closeout_field_count": len(
                final_executor_guard_closeout_fields
            ),
            "controlled_dry_run_final_executor_guard_closeout_acceptance_gate_count": len(
                final_executor_guard_closeout_acceptance_gates
            ),
            "pre_apply_replay_verifier_count": 1,
            "pre_apply_replay_verifier_field_count": len(
                pre_apply_replay_verifier_fields
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_count": summary.get(
                "controlled_dry_run_no_apply_enforcement_closeout_count", 0
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_field_count": (
                summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_field_count",
                    0,
                )
            ),
            "controlled_dry_run_no_apply_enforcement_closeout_acceptance_gate_count": (
                summary.get(
                    "controlled_dry_run_no_apply_enforcement_closeout_acceptance_gate_count",
                    0,
                )
            ),
            "final_dry_run_executor_guard_count": summary.get(
                "final_dry_run_executor_guard_count", 0
            ),
            "final_dry_run_executor_guard_field_count": summary.get(
                "final_dry_run_executor_guard_field_count", 0
            ),
            "no_apply_enforcement_verification_count": summary.get(
                "no_apply_enforcement_verification_count", 0
            ),
            "no_apply_enforcement_verification_field_count": summary.get(
                "no_apply_enforcement_verification_field_count", 0
            ),
            "post_receipt_parser_verification_count": summary.get(
                "post_receipt_parser_verification_count", 0
            ),
            "post_receipt_parser_verification_field_count": summary.get(
                "post_receipt_parser_verification_field_count", 0
            ),
            "receipt_closeout_preview_count": summary.get(
                "receipt_closeout_preview_count", 0
            ),
            "receipt_validation_report_count": summary.get(
                "receipt_validation_report_count", 0
            ),
            "receipt_validation_field_count": summary.get(
                "receipt_validation_field_count", 0
            ),
            "rollback_binding_count": summary.get("rollback_binding_count", 0),
            "post_apply_verifier_binding_count": summary.get(
                "post_apply_verifier_binding_count", 0
            ),
            "post_apply_verifier_required_count": summary.get(
                "post_apply_verifier_required_count", 0
            ),
            "same_run_truth_required_count": summary.get(
                "same_run_truth_required_count", 0
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        },
        "future_database_apply_controlled_dry_run_pre_apply_replay_verifier": (
            future_database_apply_controlled_dry_run_pre_apply_replay_verifier
        ),
        "controlled_dry_run_final_executor_guard_closeout": (
            controlled_dry_run_final_executor_guard_closeout
        ),
        "controlled_dry_run_final_executor_guard_closeout_contract": (
            controlled_dry_run_final_executor_guard_closeout_contract
        ),
        "controlled_dry_run_final_executor_guard_closeout_checks": checks,
        "source_controlled_dry_run_no_apply_enforcement_closeout_summary": summary,
        "source_controlled_dry_run_no_apply_enforcement_closeout_contract": (
            no_apply_contract
        ),
        "source_controlled_dry_run_no_apply_enforcement_closeout": (
            no_apply_closeout
        ),
        "source_database_apply_controlled_dry_run_final_dry_run_executor_guard": (
            future_guard
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_final_executor_guard_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run pre-apply replay closeout.",
            "Keep replay verification preview-only until a dedicated execution lane is explicit.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out replay verification and bind an apply executor readiness contract."""
    final_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_replay_verifier = (
        final_closeout_result.get(
            "future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
        )
        or {}
    )
    final_closeout = (
        final_closeout_result.get(
            "controlled_dry_run_final_executor_guard_closeout"
        )
        or {}
    )
    final_closeout_contract = (
        final_closeout_result.get(
            "controlled_dry_run_final_executor_guard_closeout_contract"
        )
        or {}
    )
    summary = final_closeout_result.get("summary") or {}
    safety = final_closeout_result.get("safety") or {}
    replay_verifier = final_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = final_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        final_closeout.get("no_apply_enforcement_verification") or {}
    )
    no_apply_closeout = final_closeout.get("no_apply_enforcement_closeout") or {}
    rollback_binding = final_closeout.get("rollback_binding") or {}
    verifier_binding = final_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_pre_apply_replay_closeout_id(
        final_closeout_result
    )
    apply_executor_readiness_contract_id = (
        f"{closeout_id}-apply-executor-readiness-contract"
    )
    pre_apply_replay_closeout_fields = [
        "pre_apply_replay_closeout_id",
        "source_final_executor_guard_closeout_id",
        "source_pre_apply_replay_verifier_id",
        "source_final_dry_run_executor_guard_id",
        "source_no_apply_enforcement_closeout_id",
        "dry_run_command_shape_hash",
        "apply_executor_readiness_contract_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    pre_apply_replay_closeout_acceptance_gates = [
        "final_executor_guard_closeout_ready",
        "source_chain_ids_match",
        "pre_apply_replay_verifier_ready",
        "pre_apply_replay_preview_only",
        "apply_executor_readiness_contract_bound",
        "apply_executor_readiness_contract_blocks_apply",
        "final_guard_and_no_apply_enforcement_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    apply_executor_readiness_contract_fields = [
        "contract_id",
        "source_pre_apply_replay_closeout_id",
        "source_pre_apply_replay_verifier_id",
        "source_final_dry_run_executor_guard_id",
        "required_replay_mode",
        "required_guard_status",
        "required_command_shape_hash",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_write_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_final_executor_guard_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_pre_apply_replay_verifier_missing",
        "abort_if_replay_mode_is_not_preview_only",
        "abort_if_apply_executor_readiness_contract_missing",
        "abort_if_contract_allows_apply_executor_invocation",
        "abort_if_contract_allows_endpoint_or_sql_execution",
        "abort_if_contract_allows_database_write_or_apply",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    apply_executor_readiness_contract = {
        "contract_id": apply_executor_readiness_contract_id,
        "source_pre_apply_replay_closeout_id": closeout_id,
        "source_pre_apply_replay_verifier_id": replay_verifier.get(
            "verification_id"
        ),
        "source_final_executor_guard_closeout_id": final_closeout.get(
            "final_executor_guard_closeout_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "source_no_apply_enforcement_closeout_id": no_apply_closeout.get(
            "no_apply_enforcement_closeout_id"
        ),
        "required_replay_mode": "pre_apply_replay_preview_only",
        "required_guard_status": "final_dry_run_executor_guard_preview_ready",
        "required_command_shape_hash": final_guard.get(
            "required_command_shape_hash"
        ),
        "readiness_status": "apply_executor_readiness_contract_preview_ready",
        "readiness_mode": "apply_executor_readiness_contract_preview_only",
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "apply_executor_readiness_contract_field_count": len(
            apply_executor_readiness_contract_fields
        ),
        "apply_executor_readiness_contract_fields": (
            apply_executor_readiness_contract_fields
        ),
    }
    final_executor_guard_closeout_ready = (
        final_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_final_executor_guard_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_final_executor_guard_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_final_executor_guard_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(final_closeout.get("final_executor_guard_closeout_id"))
        and final_closeout.get("final_executor_guard_closeout_id")
        == future_replay_verifier.get("final_executor_guard_closeout_id")
        == replay_verifier.get("source_final_executor_guard_closeout_id")
        == apply_executor_readiness_contract.get(
            "source_final_executor_guard_closeout_id"
        )
        and replay_verifier.get("verification_id")
        == future_replay_verifier.get("pre_apply_replay_verifier_id")
        == apply_executor_readiness_contract.get(
            "source_pre_apply_replay_verifier_id"
        )
        and final_guard.get("guard_id")
        == replay_verifier.get("source_final_dry_run_executor_guard_id")
        == apply_executor_readiness_contract.get(
            "source_final_dry_run_executor_guard_id"
        )
    )
    pre_apply_replay_verifier_ready = (
        replay_verifier.get("verifier_status")
        == "pre_apply_replay_verifier_preview_ready"
        and replay_verifier.get("verification_id")
        == future_replay_verifier.get("pre_apply_replay_verifier_id")
        and int(replay_verifier.get("pre_apply_replay_verifier_field_count") or 0)
        == 12
    )
    pre_apply_replay_preview_only = (
        replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and replay_verifier.get("dry_run_executor_invocation_allowed") is False
        and replay_verifier.get("endpoint_execution_allowed") is False
        and replay_verifier.get("sql_execution_allowed") is False
        and replay_verifier.get("database_write_allowed") is False
        and replay_verifier.get("database_apply_authorized") is False
        and replay_verifier.get("executes_database_apply") is False
        and replay_verifier.get("executes_endpoint") is False
        and replay_verifier.get("executes_sql") is False
        and replay_verifier.get("writes_database") is False
    )
    apply_executor_readiness_contract_bound = (
        bool(apply_executor_readiness_contract.get("contract_id"))
        and apply_executor_readiness_contract.get(
            "source_pre_apply_replay_closeout_id"
        )
        == closeout_id
        and apply_executor_readiness_contract.get(
            "source_pre_apply_replay_verifier_id"
        )
        == replay_verifier.get("verification_id")
        and apply_executor_readiness_contract.get("required_command_shape_hash")
        == final_guard.get("required_command_shape_hash")
        and int(
            apply_executor_readiness_contract.get(
                "apply_executor_readiness_contract_field_count"
            )
            or 0
        )
        == len(apply_executor_readiness_contract_fields)
    )
    apply_executor_readiness_contract_blocks_apply = (
        apply_executor_readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and apply_executor_readiness_contract.get(
            "dry_run_executor_invocation_allowed"
        )
        is False
        and apply_executor_readiness_contract.get("endpoint_execution_allowed")
        is False
        and apply_executor_readiness_contract.get("sql_execution_allowed") is False
        and apply_executor_readiness_contract.get("database_write_allowed")
        is False
        and apply_executor_readiness_contract.get("database_apply_authorized")
        is False
        and apply_executor_readiness_contract.get("executes_database_apply")
        is False
        and apply_executor_readiness_contract.get("executes_endpoint") is False
        and apply_executor_readiness_contract.get("executes_sql") is False
        and apply_executor_readiness_contract.get("writes_database") is False
    )
    final_guard_and_no_apply_enforcement_carried_forward = (
        final_guard.get("guard_status") == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("dry_run_executor_invocation_allowed") is False
        and final_guard.get("database_apply_authorized") is False
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("database_apply_authorized") is False
        and bool(no_apply_closeout.get("no_apply_enforcement_closeout_id"))
    )
    target_hash_locked = (
        final_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(final_closeout.get("expected_sha256"))
        and bool(final_closeout.get("actual_sha256"))
        and final_closeout.get("expected_sha256")
        == final_closeout.get("actual_sha256")
        and final_closeout.get("hash_matches") is True
        and final_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    final_executor_guard_contract_blocks_database_apply = (
        final_closeout_contract.get("executes_database_apply") is False
        and final_closeout_contract.get("executes_endpoint") is False
        and final_closeout_contract.get("executes_sql") is False
        and final_closeout_contract.get("database_apply_authorized") is False
        and final_closeout_contract.get("ready_for_database_apply_now") is False
        and final_closeout_contract.get("signs_database_apply_authorization")
        is False
        and final_closeout_contract.get("writes_database") is False
        and final_closeout_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and pre_apply_replay_preview_only
        and apply_executor_readiness_contract_blocks_apply
    )
    checks = [
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "final_executor_guard_closeout_ready",
            final_executor_guard_closeout_ready,
            {
                "result": final_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_final_executor_guard_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_final_executor_guard_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_final_executor_guard_closeout_check_count"
                ),
            },
            "wait_for_final_executor_guard_closeout_ready",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "final_executor_guard_closeout_id": final_closeout.get(
                    "final_executor_guard_closeout_id"
                ),
                "pre_apply_replay_verifier_id": replay_verifier.get(
                    "verification_id"
                ),
                "final_guard_id": final_guard.get("guard_id"),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "pre_apply_replay_verifier_ready",
            pre_apply_replay_verifier_ready,
            {
                "verification_id": replay_verifier.get("verification_id"),
                "verifier_status": replay_verifier.get("verifier_status"),
                "field_count": replay_verifier.get(
                    "pre_apply_replay_verifier_field_count"
                ),
            },
            "wait_for_pre_apply_replay_verifier_ready",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "pre_apply_replay_preview_only",
            pre_apply_replay_preview_only,
            {
                "replay_mode": replay_verifier.get("replay_mode"),
                "dry_run_executor_invocation_allowed": replay_verifier.get(
                    "dry_run_executor_invocation_allowed"
                ),
                "database_apply_authorized": replay_verifier.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_pre_apply_replay_requests_execution",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "apply_executor_readiness_contract_bound",
            apply_executor_readiness_contract_bound,
            {
                "contract_id": apply_executor_readiness_contract.get(
                    "contract_id"
                ),
                "source_pre_apply_replay_verifier_id": (
                    apply_executor_readiness_contract.get(
                        "source_pre_apply_replay_verifier_id"
                    )
                ),
                "field_count": apply_executor_readiness_contract.get(
                    "apply_executor_readiness_contract_field_count"
                ),
            },
            "wait_for_apply_executor_readiness_contract_binding",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "apply_executor_readiness_contract_blocks_apply",
            apply_executor_readiness_contract_blocks_apply,
            {
                "readiness_mode": apply_executor_readiness_contract.get(
                    "readiness_mode"
                ),
                "dry_run_executor_invocation_allowed": (
                    apply_executor_readiness_contract.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "database_apply_authorized": apply_executor_readiness_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_apply_executor_readiness_contract_allows_apply",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "final_guard_and_no_apply_enforcement_carried_forward",
            final_guard_and_no_apply_enforcement_carried_forward,
            {
                "guard_status": final_guard.get("guard_status"),
                "enforcement_status": no_apply_enforcement.get(
                    "enforcement_status"
                ),
                "no_apply_enforcement_closeout_id": no_apply_closeout.get(
                    "no_apply_enforcement_closeout_id"
                ),
            },
            "wait_for_final_guard_and_no_apply_enforcement_carry_forward",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": final_closeout.get("target_file"),
                "hash_matches": final_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    final_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(final_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "final_executor_guard_contract_blocks_database_apply",
            final_executor_guard_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_pre_apply_replay_verifier": (
                    final_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
                    )
                ),
                "database_apply_authorized": final_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": final_closeout_contract.get("writes_database"),
            },
            "abort_if_final_executor_guard_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_pre_apply_replay_closeout_check(
            "manual_review_not_required_for_safe_preview",
            final_closeout_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": final_closeout_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_apply_executor_readiness_contract = {
        "pre_apply_replay_closeout_id": closeout_id,
        "apply_executor_readiness_contract_id": (
            apply_executor_readiness_contract_id
        ),
        "source_final_executor_guard_closeout_id": final_closeout.get(
            "final_executor_guard_closeout_id"
        ),
        "source_pre_apply_replay_verifier_id": replay_verifier.get(
            "verification_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_apply_executor_readiness_contract": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_apply_executor_readiness_closeout": (
            closeout_ready
        ),
        "pre_apply_replay_closeout_ready": closeout_ready,
        "apply_executor_readiness_contract_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_pre_apply_replay_closeout = {
        "pre_apply_replay_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_pre_apply_replay_closeout"
        ),
        "source_final_executor_guard_closeout_id": final_closeout.get(
            "final_executor_guard_closeout_id"
        ),
        "source_pre_apply_replay_verifier_id": replay_verifier.get(
            "verification_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "source_no_apply_enforcement_closeout_id": no_apply_closeout.get(
            "no_apply_enforcement_closeout_id"
        ),
        "dry_run_command_shape_hash": final_guard.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_pre_apply_replay_closeout": (
            closeout_ready
        ),
        "pre_apply_replay_closeout_fields": pre_apply_replay_closeout_fields,
        "pre_apply_replay_closeout_field_count": len(
            pre_apply_replay_closeout_fields
        ),
        "pre_apply_replay_closeout_acceptance_gates": (
            pre_apply_replay_closeout_acceptance_gates
        ),
        "pre_apply_replay_closeout_acceptance_gate_count": len(
            pre_apply_replay_closeout_acceptance_gates
        ),
        "apply_executor_readiness_contract": apply_executor_readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "apply_executor_readiness_contract_field_count": len(
            apply_executor_readiness_contract_fields
        ),
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "pre_apply_replay_verifier_field_count": len(
            replay_verifier.get("pre_apply_replay_verifier_fields") or []
        ),
        "final_executor_guard_closeout": final_closeout,
        "final_executor_guard_closeout_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "no_apply_enforcement_closeout": no_apply_closeout,
        "no_apply_enforcement_closeout_count": 1,
        "target_file": final_closeout.get("target_file"),
        "expected_sha256": final_closeout.get("expected_sha256"),
        "actual_sha256": final_closeout.get("actual_sha256"),
        "hash_matches": final_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "pre_apply_replay_closeout_only": True,
        "apply_executor_readiness_contract_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_pre_apply_replay_closeout_contract = {
        "mode": "controlled_dry_run_pre_apply_replay_closeout_and_apply_executor_readiness_contract_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-pre-apply-replay-closeout"
        ),
        "source_final_executor_guard_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-final-executor-guard-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_apply_executor_readiness_contract": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_pre_apply_replay_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_pre_apply_replay_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_pre_apply_replay_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_pre_apply_replay_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_pre_apply_replay_closeout_count": 1,
            "controlled_dry_run_pre_apply_replay_closeout_field_count": len(
                pre_apply_replay_closeout_fields
            ),
            "controlled_dry_run_pre_apply_replay_closeout_acceptance_gate_count": len(
                pre_apply_replay_closeout_acceptance_gates
            ),
            "apply_executor_readiness_contract_count": 1,
            "apply_executor_readiness_contract_field_count": len(
                apply_executor_readiness_contract_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(final_closeout_result.get("success")),
        "generated_at": final_closeout_result.get("generated_at"),
        "source_policy": final_closeout_result.get("policy"),
        "stats": final_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_apply_executor_readiness_contract": (
            future_database_apply_controlled_dry_run_apply_executor_readiness_contract
        ),
        "controlled_dry_run_pre_apply_replay_closeout": (
            controlled_dry_run_pre_apply_replay_closeout
        ),
        "controlled_dry_run_pre_apply_replay_closeout_contract": (
            controlled_dry_run_pre_apply_replay_closeout_contract
        ),
        "controlled_dry_run_pre_apply_replay_closeout_checks": checks,
        "source_controlled_dry_run_final_executor_guard_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_final_executor_guard_closeout_contract": (
            final_closeout_contract
        ),
        "source_controlled_dry_run_final_executor_guard_closeout": (
            final_closeout
        ),
        "source_database_apply_controlled_dry_run_pre_apply_replay_verifier": (
            future_replay_verifier
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_pre_apply_replay_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run apply executor readiness closeout.",
            "Keep the dry-run executor invocation disabled until invocation readiness is machine-verifiable.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out apply executor readiness and bind a dry-run invocation receipt."""
    pre_apply_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_apply_contract = (
        pre_apply_closeout_result.get(
            "future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
        )
        or {}
    )
    pre_apply_closeout = (
        pre_apply_closeout_result.get(
            "controlled_dry_run_pre_apply_replay_closeout"
        )
        or {}
    )
    pre_apply_contract = (
        pre_apply_closeout_result.get(
            "controlled_dry_run_pre_apply_replay_closeout_contract"
        )
        or {}
    )
    summary = pre_apply_closeout_result.get("summary") or {}
    safety = pre_apply_closeout_result.get("safety") or {}
    readiness_contract = pre_apply_closeout.get(
        "apply_executor_readiness_contract"
    ) or {}
    replay_verifier = pre_apply_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = pre_apply_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        pre_apply_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = pre_apply_closeout.get("rollback_binding") or {}
    verifier_binding = pre_apply_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_apply_executor_readiness_closeout_id(
        pre_apply_closeout_result
    )
    receipt_id = f"{closeout_id}-dry-run-invocation-readiness-receipt"
    readiness_closeout_fields = [
        "apply_executor_readiness_closeout_id",
        "source_pre_apply_replay_closeout_id",
        "source_apply_executor_readiness_contract_id",
        "source_pre_apply_replay_verifier_id",
        "source_final_dry_run_executor_guard_id",
        "dry_run_command_shape_hash",
        "dry_run_invocation_readiness_receipt_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    readiness_closeout_acceptance_gates = [
        "pre_apply_replay_closeout_ready",
        "source_chain_ids_match",
        "apply_executor_readiness_contract_ready",
        "apply_executor_readiness_contract_blocks_invocation",
        "dry_run_invocation_readiness_receipt_bound",
        "dry_run_invocation_readiness_receipt_no_execute",
        "pre_apply_replay_and_final_guard_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    dry_run_invocation_readiness_receipt_fields = [
        "receipt_id",
        "source_apply_executor_readiness_closeout_id",
        "source_apply_executor_readiness_contract_id",
        "source_pre_apply_replay_closeout_id",
        "source_pre_apply_replay_verifier_id",
        "required_readiness_mode",
        "required_guard_status",
        "required_command_shape_hash",
        "receipt_mode",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_pre_apply_replay_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_apply_executor_readiness_contract_missing",
        "abort_if_contract_allows_dry_run_executor_invocation",
        "abort_if_invocation_readiness_receipt_missing",
        "abort_if_invocation_readiness_receipt_executes",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    dry_run_invocation_readiness_receipt = {
        "receipt_id": receipt_id,
        "source_apply_executor_readiness_closeout_id": closeout_id,
        "source_apply_executor_readiness_contract_id": readiness_contract.get(
            "contract_id"
        ),
        "source_pre_apply_replay_closeout_id": pre_apply_closeout.get(
            "pre_apply_replay_closeout_id"
        ),
        "source_pre_apply_replay_verifier_id": replay_verifier.get(
            "verification_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "required_readiness_mode": "apply_executor_readiness_contract_preview_only",
        "required_guard_status": "final_dry_run_executor_guard_preview_ready",
        "required_command_shape_hash": readiness_contract.get(
            "required_command_shape_hash"
        ),
        "receipt_status": "dry_run_invocation_readiness_receipt_preview_ready",
        "receipt_mode": "dry_run_invocation_readiness_preview_only",
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "dry_run_invocation_readiness_receipt_field_count": len(
            dry_run_invocation_readiness_receipt_fields
        ),
        "dry_run_invocation_readiness_receipt_fields": (
            dry_run_invocation_readiness_receipt_fields
        ),
    }
    pre_apply_replay_closeout_ready = (
        pre_apply_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_pre_apply_replay_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_pre_apply_replay_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_pre_apply_replay_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(pre_apply_closeout.get("pre_apply_replay_closeout_id"))
        and pre_apply_closeout.get("pre_apply_replay_closeout_id")
        == future_apply_contract.get("pre_apply_replay_closeout_id")
        == readiness_contract.get("source_pre_apply_replay_closeout_id")
        == dry_run_invocation_readiness_receipt.get(
            "source_pre_apply_replay_closeout_id"
        )
        and readiness_contract.get("contract_id")
        == future_apply_contract.get("apply_executor_readiness_contract_id")
        == dry_run_invocation_readiness_receipt.get(
            "source_apply_executor_readiness_contract_id"
        )
        and replay_verifier.get("verification_id")
        == readiness_contract.get("source_pre_apply_replay_verifier_id")
        == dry_run_invocation_readiness_receipt.get(
            "source_pre_apply_replay_verifier_id"
        )
        and final_guard.get("guard_id")
        == readiness_contract.get("source_final_dry_run_executor_guard_id")
        == dry_run_invocation_readiness_receipt.get(
            "source_final_dry_run_executor_guard_id"
        )
    )
    apply_executor_readiness_contract_ready = (
        readiness_contract.get("readiness_status")
        == "apply_executor_readiness_contract_preview_ready"
        and readiness_contract.get("contract_id")
        == future_apply_contract.get("apply_executor_readiness_contract_id")
        and int(
            readiness_contract.get(
                "apply_executor_readiness_contract_field_count"
            )
            or 0
        )
        == 12
    )
    apply_executor_readiness_contract_blocks_invocation = (
        readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and readiness_contract.get("dry_run_executor_invocation_allowed")
        is False
        and readiness_contract.get("endpoint_execution_allowed") is False
        and readiness_contract.get("sql_execution_allowed") is False
        and readiness_contract.get("database_write_allowed") is False
        and readiness_contract.get("database_apply_authorized") is False
        and readiness_contract.get("executes_database_apply") is False
        and readiness_contract.get("executes_endpoint") is False
        and readiness_contract.get("executes_sql") is False
        and readiness_contract.get("writes_database") is False
    )
    dry_run_invocation_readiness_receipt_bound = (
        bool(dry_run_invocation_readiness_receipt.get("receipt_id"))
        and dry_run_invocation_readiness_receipt.get(
            "source_apply_executor_readiness_closeout_id"
        )
        == closeout_id
        and dry_run_invocation_readiness_receipt.get(
            "source_apply_executor_readiness_contract_id"
        )
        == readiness_contract.get("contract_id")
        and dry_run_invocation_readiness_receipt.get(
            "required_command_shape_hash"
        )
        == readiness_contract.get("required_command_shape_hash")
        and int(
            dry_run_invocation_readiness_receipt.get(
                "dry_run_invocation_readiness_receipt_field_count"
            )
            or 0
        )
        == len(dry_run_invocation_readiness_receipt_fields)
    )
    dry_run_invocation_readiness_receipt_no_execute = (
        dry_run_invocation_readiness_receipt.get("receipt_mode")
        == "dry_run_invocation_readiness_preview_only"
        and dry_run_invocation_readiness_receipt.get(
            "dry_run_executor_invocation_allowed"
        )
        is False
        and dry_run_invocation_readiness_receipt.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and dry_run_invocation_readiness_receipt.get("endpoint_execution_allowed")
        is False
        and dry_run_invocation_readiness_receipt.get("sql_execution_allowed")
        is False
        and dry_run_invocation_readiness_receipt.get("database_write_allowed")
        is False
        and dry_run_invocation_readiness_receipt.get("database_apply_authorized")
        is False
        and dry_run_invocation_readiness_receipt.get("executes_database_apply")
        is False
        and dry_run_invocation_readiness_receipt.get("executes_endpoint") is False
        and dry_run_invocation_readiness_receipt.get("executes_sql") is False
        and dry_run_invocation_readiness_receipt.get("writes_database") is False
    )
    pre_apply_replay_and_final_guard_carried_forward = (
        replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and replay_verifier.get("dry_run_executor_invocation_allowed") is False
        and replay_verifier.get("database_apply_authorized") is False
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("dry_run_executor_invocation_allowed") is False
        and final_guard.get("database_apply_authorized") is False
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("database_apply_authorized") is False
    )
    target_hash_locked = (
        pre_apply_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(pre_apply_closeout.get("expected_sha256"))
        and bool(pre_apply_closeout.get("actual_sha256"))
        and pre_apply_closeout.get("expected_sha256")
        == pre_apply_closeout.get("actual_sha256")
        and pre_apply_closeout.get("hash_matches") is True
        and pre_apply_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    pre_apply_contract_blocks_database_apply = (
        pre_apply_contract.get("executes_database_apply") is False
        and pre_apply_contract.get("executes_endpoint") is False
        and pre_apply_contract.get("executes_sql") is False
        and pre_apply_contract.get("database_apply_authorized") is False
        and pre_apply_contract.get("ready_for_database_apply_now") is False
        and pre_apply_contract.get("ready_for_dry_run_executor_invocation_now")
        is False
        and pre_apply_contract.get("signs_database_apply_authorization") is False
        and pre_apply_contract.get("writes_database") is False
        and pre_apply_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and apply_executor_readiness_contract_blocks_invocation
        and dry_run_invocation_readiness_receipt_no_execute
    )
    checks = [
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "pre_apply_replay_closeout_ready",
            pre_apply_replay_closeout_ready,
            {
                "result": pre_apply_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_pre_apply_replay_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_pre_apply_replay_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_pre_apply_replay_closeout_check_count"
                ),
            },
            "wait_for_pre_apply_replay_closeout_ready",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "pre_apply_replay_closeout_id": pre_apply_closeout.get(
                    "pre_apply_replay_closeout_id"
                ),
                "apply_executor_readiness_contract_id": readiness_contract.get(
                    "contract_id"
                ),
                "pre_apply_replay_verifier_id": replay_verifier.get(
                    "verification_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "apply_executor_readiness_contract_ready",
            apply_executor_readiness_contract_ready,
            {
                "contract_id": readiness_contract.get("contract_id"),
                "readiness_status": readiness_contract.get("readiness_status"),
                "field_count": readiness_contract.get(
                    "apply_executor_readiness_contract_field_count"
                ),
            },
            "wait_for_apply_executor_readiness_contract_ready",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "apply_executor_readiness_contract_blocks_invocation",
            apply_executor_readiness_contract_blocks_invocation,
            {
                "readiness_mode": readiness_contract.get("readiness_mode"),
                "dry_run_executor_invocation_allowed": readiness_contract.get(
                    "dry_run_executor_invocation_allowed"
                ),
                "database_apply_authorized": readiness_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_apply_executor_readiness_contract_allows_invocation",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "dry_run_invocation_readiness_receipt_bound",
            dry_run_invocation_readiness_receipt_bound,
            {
                "receipt_id": dry_run_invocation_readiness_receipt.get(
                    "receipt_id"
                ),
                "source_apply_executor_readiness_contract_id": (
                    dry_run_invocation_readiness_receipt.get(
                        "source_apply_executor_readiness_contract_id"
                    )
                ),
                "field_count": dry_run_invocation_readiness_receipt.get(
                    "dry_run_invocation_readiness_receipt_field_count"
                ),
            },
            "wait_for_dry_run_invocation_readiness_receipt_binding",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "dry_run_invocation_readiness_receipt_no_execute",
            dry_run_invocation_readiness_receipt_no_execute,
            {
                "receipt_mode": dry_run_invocation_readiness_receipt.get(
                    "receipt_mode"
                ),
                "dry_run_executor_invocation_allowed": (
                    dry_run_invocation_readiness_receipt.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "ready_for_dry_run_executor_invocation_now": (
                    dry_run_invocation_readiness_receipt.get(
                        "ready_for_dry_run_executor_invocation_now"
                    )
                ),
            },
            "abort_if_dry_run_invocation_readiness_receipt_executes",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "pre_apply_replay_and_final_guard_carried_forward",
            pre_apply_replay_and_final_guard_carried_forward,
            {
                "replay_mode": replay_verifier.get("replay_mode"),
                "guard_status": final_guard.get("guard_status"),
                "enforcement_status": no_apply_enforcement.get(
                    "enforcement_status"
                ),
            },
            "wait_for_pre_apply_replay_and_final_guard_carry_forward",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": pre_apply_closeout.get("target_file"),
                "hash_matches": pre_apply_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    pre_apply_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(pre_apply_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "pre_apply_replay_contract_blocks_database_apply",
            pre_apply_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_apply_executor_readiness_contract": (
                    pre_apply_contract.get(
                        "permits_future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
                    )
                ),
                "database_apply_authorized": pre_apply_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": pre_apply_contract.get("writes_database"),
            },
            "abort_if_pre_apply_replay_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_apply_executor_readiness_closeout_check(
            "manual_review_not_required_for_safe_preview",
            pre_apply_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": pre_apply_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_invocation_readiness_receipt = {
        "apply_executor_readiness_closeout_id": closeout_id,
        "dry_run_invocation_readiness_receipt_id": receipt_id,
        "source_pre_apply_replay_closeout_id": pre_apply_closeout.get(
            "pre_apply_replay_closeout_id"
        ),
        "source_apply_executor_readiness_contract_id": readiness_contract.get(
            "contract_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_invocation_readiness_receipt": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_invocation_receipt_closeout": (
            closeout_ready
        ),
        "apply_executor_readiness_closeout_ready": closeout_ready,
        "dry_run_invocation_readiness_receipt_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_apply_executor_readiness_closeout = {
        "apply_executor_readiness_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_apply_executor_readiness_closeout"
        ),
        "source_pre_apply_replay_closeout_id": pre_apply_closeout.get(
            "pre_apply_replay_closeout_id"
        ),
        "source_apply_executor_readiness_contract_id": readiness_contract.get(
            "contract_id"
        ),
        "source_pre_apply_replay_verifier_id": replay_verifier.get(
            "verification_id"
        ),
        "source_final_dry_run_executor_guard_id": final_guard.get("guard_id"),
        "dry_run_command_shape_hash": readiness_contract.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_apply_executor_readiness_closeout": (
            closeout_ready
        ),
        "apply_executor_readiness_closeout_fields": readiness_closeout_fields,
        "apply_executor_readiness_closeout_field_count": len(
            readiness_closeout_fields
        ),
        "apply_executor_readiness_closeout_acceptance_gates": (
            readiness_closeout_acceptance_gates
        ),
        "apply_executor_readiness_closeout_acceptance_gate_count": len(
            readiness_closeout_acceptance_gates
        ),
        "dry_run_invocation_readiness_receipt": (
            dry_run_invocation_readiness_receipt
        ),
        "dry_run_invocation_readiness_receipt_count": 1,
        "dry_run_invocation_readiness_receipt_field_count": len(
            dry_run_invocation_readiness_receipt_fields
        ),
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": pre_apply_closeout.get("target_file"),
        "expected_sha256": pre_apply_closeout.get("expected_sha256"),
        "actual_sha256": pre_apply_closeout.get("actual_sha256"),
        "hash_matches": pre_apply_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "apply_executor_readiness_closeout_only": True,
        "dry_run_invocation_readiness_receipt_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_apply_executor_readiness_closeout_contract = {
        "mode": "controlled_dry_run_apply_executor_readiness_closeout_and_dry_run_invocation_readiness_receipt_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-apply-executor-readiness-closeout"
        ),
        "source_pre_apply_replay_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-pre-apply-replay-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_invocation_readiness_receipt": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_apply_executor_readiness_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_apply_executor_readiness_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_apply_executor_readiness_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_apply_executor_readiness_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_apply_executor_readiness_closeout_count": 1,
            "controlled_dry_run_apply_executor_readiness_closeout_field_count": len(
                readiness_closeout_fields
            ),
            "controlled_dry_run_apply_executor_readiness_closeout_acceptance_gate_count": len(
                readiness_closeout_acceptance_gates
            ),
            "dry_run_invocation_readiness_receipt_count": 1,
            "dry_run_invocation_readiness_receipt_field_count": len(
                dry_run_invocation_readiness_receipt_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(pre_apply_closeout_result.get("success")),
        "generated_at": pre_apply_closeout_result.get("generated_at"),
        "source_policy": pre_apply_closeout_result.get("policy"),
        "stats": pre_apply_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_invocation_readiness_receipt": (
            future_database_apply_controlled_dry_run_invocation_readiness_receipt
        ),
        "controlled_dry_run_apply_executor_readiness_closeout": (
            controlled_dry_run_apply_executor_readiness_closeout
        ),
        "controlled_dry_run_apply_executor_readiness_closeout_contract": (
            controlled_dry_run_apply_executor_readiness_closeout_contract
        ),
        "controlled_dry_run_apply_executor_readiness_closeout_checks": checks,
        "source_controlled_dry_run_pre_apply_replay_closeout_summary": summary,
        "source_controlled_dry_run_pre_apply_replay_closeout_contract": (
            pre_apply_contract
        ),
        "source_controlled_dry_run_pre_apply_replay_closeout": (
            pre_apply_closeout
        ),
        "source_database_apply_controlled_dry_run_apply_executor_readiness_contract": (
            future_apply_contract
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_apply_executor_readiness_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run invocation receipt closeout.",
            "Keep actual dry-run executor invocation disabled until a dedicated no-write invocation lane is machine-verifiable.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out invocation readiness receipt and bind a no-write package."""
    readiness_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_receipt = (
        readiness_closeout_result.get(
            "future_database_apply_controlled_dry_run_invocation_readiness_receipt"
        )
        or {}
    )
    readiness_closeout = (
        readiness_closeout_result.get(
            "controlled_dry_run_apply_executor_readiness_closeout"
        )
        or {}
    )
    readiness_closeout_contract = (
        readiness_closeout_result.get(
            "controlled_dry_run_apply_executor_readiness_closeout_contract"
        )
        or {}
    )
    summary = readiness_closeout_result.get("summary") or {}
    safety = readiness_closeout_result.get("safety") or {}
    receipt = readiness_closeout.get("dry_run_invocation_readiness_receipt") or {}
    readiness_contract = (
        readiness_closeout.get("apply_executor_readiness_contract") or {}
    )
    pre_apply_closeout = readiness_closeout.get("pre_apply_replay_closeout") or {}
    replay_verifier = readiness_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = readiness_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        readiness_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = readiness_closeout.get("rollback_binding") or {}
    verifier_binding = readiness_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_invocation_receipt_closeout_id(
        readiness_closeout_result
    )
    package_id = f"{closeout_id}-no-write-invocation-package"
    invocation_receipt_closeout_fields = [
        "invocation_receipt_closeout_id",
        "source_apply_executor_readiness_closeout_id",
        "source_dry_run_invocation_readiness_receipt_id",
        "source_apply_executor_readiness_contract_id",
        "source_pre_apply_replay_closeout_id",
        "dry_run_command_shape_hash",
        "no_write_invocation_package_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    invocation_receipt_closeout_acceptance_gates = [
        "apply_executor_readiness_closeout_ready",
        "source_chain_ids_match",
        "dry_run_invocation_readiness_receipt_ready",
        "dry_run_invocation_readiness_receipt_no_execute",
        "no_write_invocation_package_bound",
        "no_write_invocation_package_blocks_execution",
        "apply_executor_readiness_and_replay_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    no_write_invocation_package_fields = [
        "package_id",
        "source_invocation_receipt_closeout_id",
        "source_dry_run_invocation_readiness_receipt_id",
        "source_apply_executor_readiness_closeout_id",
        "source_apply_executor_readiness_contract_id",
        "required_receipt_mode",
        "required_command_shape_hash",
        "package_mode",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_apply_executor_readiness_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_dry_run_invocation_readiness_receipt_missing",
        "abort_if_invocation_readiness_receipt_executes",
        "abort_if_no_write_invocation_package_missing",
        "abort_if_no_write_invocation_package_executes",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    no_write_invocation_package = {
        "package_id": package_id,
        "source_invocation_receipt_closeout_id": closeout_id,
        "source_dry_run_invocation_readiness_receipt_id": receipt.get(
            "receipt_id"
        ),
        "source_apply_executor_readiness_closeout_id": readiness_closeout.get(
            "apply_executor_readiness_closeout_id"
        ),
        "source_apply_executor_readiness_contract_id": readiness_contract.get(
            "contract_id"
        ),
        "source_pre_apply_replay_closeout_id": pre_apply_closeout.get(
            "pre_apply_replay_closeout_id"
        ),
        "required_receipt_mode": "dry_run_invocation_readiness_preview_only",
        "required_command_shape_hash": receipt.get("required_command_shape_hash"),
        "package_status": "no_write_invocation_package_preview_ready",
        "package_mode": "no_write_invocation_package_preview_only",
        "dry_run_executor_invocation_allowed": False,
        "ready_for_no_write_dry_run_invocation_package_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "writes_package_artifact": False,
        "reads_secret_in_preview": False,
        "no_write_invocation_package_field_count": len(
            no_write_invocation_package_fields
        ),
        "no_write_invocation_package_fields": no_write_invocation_package_fields,
    }
    apply_executor_readiness_closeout_ready = (
        readiness_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_apply_executor_readiness_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_apply_executor_readiness_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_apply_executor_readiness_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(readiness_closeout.get("apply_executor_readiness_closeout_id"))
        and readiness_closeout.get("apply_executor_readiness_closeout_id")
        == future_receipt.get("apply_executor_readiness_closeout_id")
        == receipt.get("source_apply_executor_readiness_closeout_id")
        == no_write_invocation_package.get(
            "source_apply_executor_readiness_closeout_id"
        )
        and receipt.get("receipt_id")
        == future_receipt.get("dry_run_invocation_readiness_receipt_id")
        == no_write_invocation_package.get(
            "source_dry_run_invocation_readiness_receipt_id"
        )
        and readiness_contract.get("contract_id")
        == receipt.get("source_apply_executor_readiness_contract_id")
        == no_write_invocation_package.get(
            "source_apply_executor_readiness_contract_id"
        )
        and pre_apply_closeout.get("pre_apply_replay_closeout_id")
        == receipt.get("source_pre_apply_replay_closeout_id")
        == no_write_invocation_package.get("source_pre_apply_replay_closeout_id")
    )
    dry_run_invocation_readiness_receipt_ready = (
        receipt.get("receipt_status")
        == "dry_run_invocation_readiness_receipt_preview_ready"
        and receipt.get("receipt_id")
        == future_receipt.get("dry_run_invocation_readiness_receipt_id")
        and int(receipt.get("dry_run_invocation_readiness_receipt_field_count") or 0)
        == 12
    )
    dry_run_invocation_readiness_receipt_no_execute = (
        receipt.get("receipt_mode") == "dry_run_invocation_readiness_preview_only"
        and receipt.get("dry_run_executor_invocation_allowed") is False
        and receipt.get("ready_for_dry_run_executor_invocation_now") is False
        and receipt.get("endpoint_execution_allowed") is False
        and receipt.get("sql_execution_allowed") is False
        and receipt.get("database_write_allowed") is False
        and receipt.get("database_apply_authorized") is False
        and receipt.get("executes_database_apply") is False
        and receipt.get("executes_endpoint") is False
        and receipt.get("executes_sql") is False
        and receipt.get("writes_database") is False
    )
    no_write_invocation_package_bound = (
        bool(no_write_invocation_package.get("package_id"))
        and no_write_invocation_package.get(
            "source_invocation_receipt_closeout_id"
        )
        == closeout_id
        and no_write_invocation_package.get(
            "source_dry_run_invocation_readiness_receipt_id"
        )
        == receipt.get("receipt_id")
        and no_write_invocation_package.get("required_command_shape_hash")
        == receipt.get("required_command_shape_hash")
        and int(
            no_write_invocation_package.get(
                "no_write_invocation_package_field_count"
            )
            or 0
        )
        == len(no_write_invocation_package_fields)
    )
    no_write_invocation_package_blocks_execution = (
        no_write_invocation_package.get("package_mode")
        == "no_write_invocation_package_preview_only"
        and no_write_invocation_package.get("dry_run_executor_invocation_allowed")
        is False
        and no_write_invocation_package.get(
            "ready_for_no_write_dry_run_invocation_package_now"
        )
        is False
        and no_write_invocation_package.get(
            "ready_for_actual_dry_run_execution_now"
        )
        is False
        and no_write_invocation_package.get("endpoint_execution_allowed") is False
        and no_write_invocation_package.get("sql_execution_allowed") is False
        and no_write_invocation_package.get("database_write_allowed") is False
        and no_write_invocation_package.get("database_apply_authorized") is False
        and no_write_invocation_package.get("executes_database_apply") is False
        and no_write_invocation_package.get("executes_endpoint") is False
        and no_write_invocation_package.get("executes_sql") is False
        and no_write_invocation_package.get("writes_database") is False
    )
    apply_executor_readiness_and_replay_carried_forward = (
        readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and readiness_contract.get("dry_run_executor_invocation_allowed")
        is False
        and readiness_contract.get("database_apply_authorized") is False
        and replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and replay_verifier.get("dry_run_executor_invocation_allowed") is False
        and replay_verifier.get("database_apply_authorized") is False
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("dry_run_executor_invocation_allowed") is False
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("database_apply_authorized") is False
    )
    target_hash_locked = (
        readiness_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(readiness_closeout.get("expected_sha256"))
        and bool(readiness_closeout.get("actual_sha256"))
        and readiness_closeout.get("expected_sha256")
        == readiness_closeout.get("actual_sha256")
        and readiness_closeout.get("hash_matches") is True
        and readiness_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    readiness_closeout_contract_blocks_database_apply = (
        readiness_closeout_contract.get("executes_database_apply") is False
        and readiness_closeout_contract.get("executes_endpoint") is False
        and readiness_closeout_contract.get("executes_sql") is False
        and readiness_closeout_contract.get("database_apply_authorized") is False
        and readiness_closeout_contract.get("ready_for_database_apply_now")
        is False
        and readiness_closeout_contract.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and readiness_closeout_contract.get("ready_for_actual_dry_run_execution_now")
        is False
        and readiness_closeout_contract.get("signs_database_apply_authorization")
        is False
        and readiness_closeout_contract.get("writes_database") is False
        and readiness_closeout_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and dry_run_invocation_readiness_receipt_no_execute
        and no_write_invocation_package_blocks_execution
    )
    checks = [
        _controlled_dry_run_invocation_receipt_closeout_check(
            "apply_executor_readiness_closeout_ready",
            apply_executor_readiness_closeout_ready,
            {
                "result": readiness_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_apply_executor_readiness_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_apply_executor_readiness_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_apply_executor_readiness_closeout_check_count"
                ),
            },
            "wait_for_apply_executor_readiness_closeout_ready",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "apply_executor_readiness_closeout_id": readiness_closeout.get(
                    "apply_executor_readiness_closeout_id"
                ),
                "dry_run_invocation_readiness_receipt_id": receipt.get(
                    "receipt_id"
                ),
                "apply_executor_readiness_contract_id": readiness_contract.get(
                    "contract_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "dry_run_invocation_readiness_receipt_ready",
            dry_run_invocation_readiness_receipt_ready,
            {
                "receipt_id": receipt.get("receipt_id"),
                "receipt_status": receipt.get("receipt_status"),
                "field_count": receipt.get(
                    "dry_run_invocation_readiness_receipt_field_count"
                ),
            },
            "wait_for_dry_run_invocation_readiness_receipt_ready",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "dry_run_invocation_readiness_receipt_no_execute",
            dry_run_invocation_readiness_receipt_no_execute,
            {
                "receipt_mode": receipt.get("receipt_mode"),
                "dry_run_executor_invocation_allowed": receipt.get(
                    "dry_run_executor_invocation_allowed"
                ),
                "ready_for_dry_run_executor_invocation_now": receipt.get(
                    "ready_for_dry_run_executor_invocation_now"
                ),
            },
            "abort_if_dry_run_invocation_readiness_receipt_executes",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "no_write_invocation_package_bound",
            no_write_invocation_package_bound,
            {
                "package_id": no_write_invocation_package.get("package_id"),
                "source_dry_run_invocation_readiness_receipt_id": (
                    no_write_invocation_package.get(
                        "source_dry_run_invocation_readiness_receipt_id"
                    )
                ),
                "field_count": no_write_invocation_package.get(
                    "no_write_invocation_package_field_count"
                ),
            },
            "wait_for_no_write_invocation_package_binding",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "no_write_invocation_package_blocks_execution",
            no_write_invocation_package_blocks_execution,
            {
                "package_mode": no_write_invocation_package.get("package_mode"),
                "dry_run_executor_invocation_allowed": (
                    no_write_invocation_package.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "ready_for_actual_dry_run_execution_now": (
                    no_write_invocation_package.get(
                        "ready_for_actual_dry_run_execution_now"
                    )
                ),
            },
            "abort_if_no_write_invocation_package_executes",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "apply_executor_readiness_and_replay_carried_forward",
            apply_executor_readiness_and_replay_carried_forward,
            {
                "readiness_mode": readiness_contract.get("readiness_mode"),
                "replay_mode": replay_verifier.get("replay_mode"),
                "guard_status": final_guard.get("guard_status"),
            },
            "wait_for_apply_executor_readiness_and_replay_carry_forward",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": readiness_closeout.get("target_file"),
                "hash_matches": readiness_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    readiness_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(
                    readiness_closeout.get("actual_sha256")
                ),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "apply_executor_readiness_closeout_contract_blocks_database_apply",
            readiness_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_invocation_readiness_receipt": (
                    readiness_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_invocation_readiness_receipt"
                    )
                ),
                "database_apply_authorized": readiness_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": readiness_closeout_contract.get(
                    "writes_database"
                ),
            },
            "abort_if_apply_executor_readiness_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_invocation_receipt_closeout_check(
            "manual_review_not_required_for_safe_preview",
            readiness_closeout_contract.get("manual_review_mode")
            == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": readiness_closeout_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_no_write_invocation_package = {
        "invocation_receipt_closeout_id": closeout_id,
        "no_write_invocation_package_id": package_id,
        "source_apply_executor_readiness_closeout_id": readiness_closeout.get(
            "apply_executor_readiness_closeout_id"
        ),
        "source_dry_run_invocation_readiness_receipt_id": receipt.get(
            "receipt_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_write_invocation_package": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_no_write_invocation_package_closeout": (
            closeout_ready
        ),
        "invocation_receipt_closeout_ready": closeout_ready,
        "no_write_invocation_package_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_invocation_receipt_closeout = {
        "invocation_receipt_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_invocation_receipt_closeout"
        ),
        "source_apply_executor_readiness_closeout_id": readiness_closeout.get(
            "apply_executor_readiness_closeout_id"
        ),
        "source_dry_run_invocation_readiness_receipt_id": receipt.get(
            "receipt_id"
        ),
        "source_apply_executor_readiness_contract_id": readiness_contract.get(
            "contract_id"
        ),
        "source_pre_apply_replay_closeout_id": pre_apply_closeout.get(
            "pre_apply_replay_closeout_id"
        ),
        "dry_run_command_shape_hash": receipt.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_invocation_receipt_closeout": (
            closeout_ready
        ),
        "invocation_receipt_closeout_fields": invocation_receipt_closeout_fields,
        "invocation_receipt_closeout_field_count": len(
            invocation_receipt_closeout_fields
        ),
        "invocation_receipt_closeout_acceptance_gates": (
            invocation_receipt_closeout_acceptance_gates
        ),
        "invocation_receipt_closeout_acceptance_gate_count": len(
            invocation_receipt_closeout_acceptance_gates
        ),
        "no_write_invocation_package": no_write_invocation_package,
        "no_write_invocation_package_count": 1,
        "no_write_invocation_package_field_count": len(
            no_write_invocation_package_fields
        ),
        "dry_run_invocation_readiness_receipt": receipt,
        "dry_run_invocation_readiness_receipt_count": 1,
        "apply_executor_readiness_closeout": readiness_closeout,
        "apply_executor_readiness_closeout_count": 1,
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": readiness_closeout.get("target_file"),
        "expected_sha256": readiness_closeout.get("expected_sha256"),
        "actual_sha256": readiness_closeout.get("actual_sha256"),
        "hash_matches": readiness_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "invocation_receipt_closeout_only": True,
        "no_write_invocation_package_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_invocation_receipt_closeout_contract = {
        "mode": "controlled_dry_run_invocation_receipt_closeout_and_no_write_invocation_package_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-invocation-receipt-closeout"
        ),
        "source_apply_executor_readiness_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-apply-executor-readiness-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_no_write_invocation_package": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_invocation_receipt_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_invocation_receipt_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_invocation_receipt_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_invocation_receipt_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_invocation_receipt_closeout_count": 1,
            "controlled_dry_run_invocation_receipt_closeout_field_count": len(
                invocation_receipt_closeout_fields
            ),
            "controlled_dry_run_invocation_receipt_closeout_acceptance_gate_count": len(
                invocation_receipt_closeout_acceptance_gates
            ),
            "no_write_invocation_package_count": 1,
            "no_write_invocation_package_field_count": len(
                no_write_invocation_package_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(readiness_closeout_result.get("success")),
        "generated_at": readiness_closeout_result.get("generated_at"),
        "source_policy": readiness_closeout_result.get("policy"),
        "stats": readiness_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_no_write_invocation_package": (
            future_database_apply_controlled_dry_run_no_write_invocation_package
        ),
        "controlled_dry_run_invocation_receipt_closeout": (
            controlled_dry_run_invocation_receipt_closeout
        ),
        "controlled_dry_run_invocation_receipt_closeout_contract": (
            controlled_dry_run_invocation_receipt_closeout_contract
        ),
        "controlled_dry_run_invocation_receipt_closeout_checks": checks,
        "source_controlled_dry_run_apply_executor_readiness_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_apply_executor_readiness_closeout_contract": (
            readiness_closeout_contract
        ),
        "source_controlled_dry_run_apply_executor_readiness_closeout": (
            readiness_closeout
        ),
        "source_database_apply_controlled_dry_run_invocation_readiness_receipt": (
            future_receipt
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_invocation_receipt_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run no-write invocation package closeout.",
            "Keep actual dry-run executor invocation disabled until a dedicated execution-preflight guard is machine-verifiable.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the no-write invocation package and bind execution preflight."""
    invocation_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_package = (
        invocation_closeout_result.get(
            "future_database_apply_controlled_dry_run_no_write_invocation_package"
        )
        or {}
    )
    invocation_closeout = (
        invocation_closeout_result.get(
            "controlled_dry_run_invocation_receipt_closeout"
        )
        or {}
    )
    invocation_closeout_contract = (
        invocation_closeout_result.get(
            "controlled_dry_run_invocation_receipt_closeout_contract"
        )
        or {}
    )
    summary = invocation_closeout_result.get("summary") or {}
    safety = invocation_closeout_result.get("safety") or {}
    package = invocation_closeout.get("no_write_invocation_package") or {}
    receipt = (
        invocation_closeout.get("dry_run_invocation_readiness_receipt") or {}
    )
    readiness_closeout = (
        invocation_closeout.get("apply_executor_readiness_closeout") or {}
    )
    readiness_contract = (
        invocation_closeout.get("apply_executor_readiness_contract") or {}
    )
    pre_apply_closeout = invocation_closeout.get("pre_apply_replay_closeout") or {}
    replay_verifier = invocation_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = invocation_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        invocation_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = invocation_closeout.get("rollback_binding") or {}
    verifier_binding = invocation_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = (
        _db_apply_controlled_dry_run_no_write_invocation_package_closeout_id(
            invocation_closeout_result
        )
    )
    guard_id = f"{closeout_id}-execution-preflight-guard"
    package_closeout_fields = [
        "no_write_invocation_package_closeout_id",
        "source_invocation_receipt_closeout_id",
        "source_no_write_invocation_package_id",
        "source_dry_run_invocation_readiness_receipt_id",
        "source_apply_executor_readiness_closeout_id",
        "required_command_shape_hash",
        "execution_preflight_guard_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    package_closeout_acceptance_gates = [
        "invocation_receipt_closeout_ready",
        "source_chain_ids_match",
        "no_write_invocation_package_ready",
        "no_write_invocation_package_no_execute",
        "execution_preflight_guard_bound",
        "execution_preflight_guard_blocks_execution",
        "invocation_receipt_and_apply_readiness_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    execution_preflight_guard_fields = [
        "guard_id",
        "source_no_write_invocation_package_closeout_id",
        "source_no_write_invocation_package_id",
        "source_invocation_receipt_closeout_id",
        "source_dry_run_invocation_readiness_receipt_id",
        "required_package_mode",
        "required_command_shape_hash",
        "guard_mode",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_invocation_receipt_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_no_write_invocation_package_missing",
        "abort_if_no_write_invocation_package_executes",
        "abort_if_execution_preflight_guard_missing",
        "abort_if_execution_preflight_guard_executes",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    execution_preflight_guard = {
        "guard_id": guard_id,
        "source_no_write_invocation_package_closeout_id": closeout_id,
        "source_no_write_invocation_package_id": package.get("package_id"),
        "source_invocation_receipt_closeout_id": invocation_closeout.get(
            "invocation_receipt_closeout_id"
        ),
        "source_dry_run_invocation_readiness_receipt_id": receipt.get(
            "receipt_id"
        ),
        "source_apply_executor_readiness_closeout_id": readiness_closeout.get(
            "apply_executor_readiness_closeout_id"
        ),
        "required_package_mode": "no_write_invocation_package_preview_only",
        "required_command_shape_hash": package.get("required_command_shape_hash"),
        "guard_status": "execution_preflight_guard_preview_ready",
        "guard_mode": "execution_preflight_guard_preview_only",
        "dry_run_executor_invocation_allowed": False,
        "ready_for_execution_preflight_guard_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "writes_guard_artifact": False,
        "reads_secret_in_preview": False,
        "execution_preflight_guard_field_count": len(
            execution_preflight_guard_fields
        ),
        "execution_preflight_guard_fields": execution_preflight_guard_fields,
    }
    invocation_receipt_closeout_ready = (
        invocation_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_invocation_receipt_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_invocation_receipt_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_invocation_receipt_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(invocation_closeout.get("invocation_receipt_closeout_id"))
        and invocation_closeout.get("invocation_receipt_closeout_id")
        == future_package.get("invocation_receipt_closeout_id")
        == package.get("source_invocation_receipt_closeout_id")
        == execution_preflight_guard.get("source_invocation_receipt_closeout_id")
        and package.get("package_id")
        == future_package.get("no_write_invocation_package_id")
        == execution_preflight_guard.get("source_no_write_invocation_package_id")
        and receipt.get("receipt_id")
        == future_package.get("source_dry_run_invocation_readiness_receipt_id")
        == package.get("source_dry_run_invocation_readiness_receipt_id")
        == execution_preflight_guard.get(
            "source_dry_run_invocation_readiness_receipt_id"
        )
        and readiness_closeout.get("apply_executor_readiness_closeout_id")
        == future_package.get("source_apply_executor_readiness_closeout_id")
        == package.get("source_apply_executor_readiness_closeout_id")
        == execution_preflight_guard.get(
            "source_apply_executor_readiness_closeout_id"
        )
    )
    no_write_invocation_package_ready = (
        package.get("package_status") == "no_write_invocation_package_preview_ready"
        and package.get("package_id")
        == future_package.get("no_write_invocation_package_id")
        and int(package.get("no_write_invocation_package_field_count") or 0)
        == 12
    )
    no_write_invocation_package_no_execute = (
        package.get("package_mode") == "no_write_invocation_package_preview_only"
        and package.get("dry_run_executor_invocation_allowed") is False
        and package.get("ready_for_no_write_dry_run_invocation_package_now")
        is False
        and package.get("ready_for_actual_dry_run_execution_now") is False
        and package.get("endpoint_execution_allowed") is False
        and package.get("sql_execution_allowed") is False
        and package.get("database_write_allowed") is False
        and package.get("database_apply_authorized") is False
        and package.get("executes_database_apply") is False
        and package.get("executes_endpoint") is False
        and package.get("executes_sql") is False
        and package.get("writes_database") is False
    )
    execution_preflight_guard_bound = (
        bool(execution_preflight_guard.get("guard_id"))
        and execution_preflight_guard.get(
            "source_no_write_invocation_package_closeout_id"
        )
        == closeout_id
        and execution_preflight_guard.get("source_no_write_invocation_package_id")
        == package.get("package_id")
        and execution_preflight_guard.get("required_command_shape_hash")
        == package.get("required_command_shape_hash")
        and int(
            execution_preflight_guard.get(
                "execution_preflight_guard_field_count"
            )
            or 0
        )
        == len(execution_preflight_guard_fields)
    )
    execution_preflight_guard_blocks_execution = (
        execution_preflight_guard.get("guard_mode")
        == "execution_preflight_guard_preview_only"
        and execution_preflight_guard.get("dry_run_executor_invocation_allowed")
        is False
        and execution_preflight_guard.get("ready_for_execution_preflight_guard_now")
        is False
        and execution_preflight_guard.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and execution_preflight_guard.get("ready_for_actual_dry_run_execution_now")
        is False
        and execution_preflight_guard.get("endpoint_execution_allowed") is False
        and execution_preflight_guard.get("sql_execution_allowed") is False
        and execution_preflight_guard.get("database_write_allowed") is False
        and execution_preflight_guard.get("database_apply_authorized") is False
        and execution_preflight_guard.get("executes_database_apply") is False
        and execution_preflight_guard.get("executes_endpoint") is False
        and execution_preflight_guard.get("executes_sql") is False
        and execution_preflight_guard.get("writes_database") is False
    )
    invocation_receipt_and_apply_readiness_carried_forward = (
        receipt.get("receipt_mode") == "dry_run_invocation_readiness_preview_only"
        and receipt.get("dry_run_executor_invocation_allowed") is False
        and readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and readiness_contract.get("dry_run_executor_invocation_allowed")
        is False
        and replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and replay_verifier.get("database_apply_authorized") is False
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("dry_run_executor_invocation_allowed") is False
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("database_apply_authorized") is False
    )
    target_hash_locked = (
        invocation_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(invocation_closeout.get("expected_sha256"))
        and bool(invocation_closeout.get("actual_sha256"))
        and invocation_closeout.get("expected_sha256")
        == invocation_closeout.get("actual_sha256")
        and invocation_closeout.get("hash_matches") is True
        and invocation_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    invocation_receipt_closeout_contract_blocks_database_apply = (
        invocation_closeout_contract.get("executes_database_apply") is False
        and invocation_closeout_contract.get("executes_endpoint") is False
        and invocation_closeout_contract.get("executes_sql") is False
        and invocation_closeout_contract.get("database_apply_authorized") is False
        and invocation_closeout_contract.get("ready_for_database_apply_now")
        is False
        and invocation_closeout_contract.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and invocation_closeout_contract.get(
            "ready_for_actual_dry_run_execution_now"
        )
        is False
        and invocation_closeout_contract.get("signs_database_apply_authorization")
        is False
        and invocation_closeout_contract.get("writes_database") is False
        and invocation_closeout_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and no_write_invocation_package_no_execute
        and execution_preflight_guard_blocks_execution
    )
    checks = [
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "invocation_receipt_closeout_ready",
            invocation_receipt_closeout_ready,
            {
                "result": invocation_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_invocation_receipt_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_invocation_receipt_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_invocation_receipt_closeout_check_count"
                ),
            },
            "wait_for_invocation_receipt_closeout_ready",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "invocation_receipt_closeout_id": invocation_closeout.get(
                    "invocation_receipt_closeout_id"
                ),
                "no_write_invocation_package_id": package.get("package_id"),
                "dry_run_invocation_readiness_receipt_id": receipt.get(
                    "receipt_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "no_write_invocation_package_ready",
            no_write_invocation_package_ready,
            {
                "package_id": package.get("package_id"),
                "package_status": package.get("package_status"),
                "field_count": package.get("no_write_invocation_package_field_count"),
            },
            "wait_for_no_write_invocation_package_ready",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "no_write_invocation_package_no_execute",
            no_write_invocation_package_no_execute,
            {
                "package_mode": package.get("package_mode"),
                "dry_run_executor_invocation_allowed": package.get(
                    "dry_run_executor_invocation_allowed"
                ),
                "ready_for_actual_dry_run_execution_now": package.get(
                    "ready_for_actual_dry_run_execution_now"
                ),
            },
            "abort_if_no_write_invocation_package_executes",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "execution_preflight_guard_bound",
            execution_preflight_guard_bound,
            {
                "guard_id": execution_preflight_guard.get("guard_id"),
                "source_no_write_invocation_package_id": (
                    execution_preflight_guard.get(
                        "source_no_write_invocation_package_id"
                    )
                ),
                "field_count": execution_preflight_guard.get(
                    "execution_preflight_guard_field_count"
                ),
            },
            "wait_for_execution_preflight_guard_binding",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "execution_preflight_guard_blocks_execution",
            execution_preflight_guard_blocks_execution,
            {
                "guard_mode": execution_preflight_guard.get("guard_mode"),
                "dry_run_executor_invocation_allowed": (
                    execution_preflight_guard.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "ready_for_actual_dry_run_execution_now": (
                    execution_preflight_guard.get(
                        "ready_for_actual_dry_run_execution_now"
                    )
                ),
            },
            "abort_if_execution_preflight_guard_executes",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "invocation_receipt_and_apply_readiness_carried_forward",
            invocation_receipt_and_apply_readiness_carried_forward,
            {
                "receipt_mode": receipt.get("receipt_mode"),
                "readiness_mode": readiness_contract.get("readiness_mode"),
                "guard_status": final_guard.get("guard_status"),
            },
            "wait_for_invocation_receipt_and_apply_readiness_carry_forward",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": invocation_closeout.get("target_file"),
                "hash_matches": invocation_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    invocation_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(
                    invocation_closeout.get("actual_sha256")
                ),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "invocation_receipt_closeout_contract_blocks_database_apply",
            invocation_receipt_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_no_write_invocation_package": (
                    invocation_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_no_write_invocation_package"
                    )
                ),
                "database_apply_authorized": invocation_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": invocation_closeout_contract.get(
                    "writes_database"
                ),
            },
            "abort_if_invocation_receipt_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_no_write_invocation_package_closeout_check(
            "manual_review_not_required_for_safe_preview",
            invocation_closeout_contract.get("manual_review_mode")
            == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": invocation_closeout_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_execution_preflight_guard = {
        "no_write_invocation_package_closeout_id": closeout_id,
        "execution_preflight_guard_id": guard_id,
        "source_invocation_receipt_closeout_id": invocation_closeout.get(
            "invocation_receipt_closeout_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "source_dry_run_invocation_readiness_receipt_id": receipt.get(
            "receipt_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_preflight_guard": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_execution_preflight_guard_closeout": (
            closeout_ready
        ),
        "no_write_invocation_package_closeout_ready": closeout_ready,
        "execution_preflight_guard_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_no_write_invocation_package_closeout = {
        "no_write_invocation_package_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_no_write_invocation_package_closeout"
        ),
        "source_invocation_receipt_closeout_id": invocation_closeout.get(
            "invocation_receipt_closeout_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "source_dry_run_invocation_readiness_receipt_id": receipt.get(
            "receipt_id"
        ),
        "source_apply_executor_readiness_closeout_id": readiness_closeout.get(
            "apply_executor_readiness_closeout_id"
        ),
        "required_command_shape_hash": package.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_write_invocation_package_closeout": (
            closeout_ready
        ),
        "no_write_invocation_package_closeout_fields": package_closeout_fields,
        "no_write_invocation_package_closeout_field_count": len(
            package_closeout_fields
        ),
        "no_write_invocation_package_closeout_acceptance_gates": (
            package_closeout_acceptance_gates
        ),
        "no_write_invocation_package_closeout_acceptance_gate_count": len(
            package_closeout_acceptance_gates
        ),
        "execution_preflight_guard": execution_preflight_guard,
        "execution_preflight_guard_count": 1,
        "execution_preflight_guard_field_count": len(
            execution_preflight_guard_fields
        ),
        "no_write_invocation_package": package,
        "no_write_invocation_package_count": 1,
        "invocation_receipt_closeout": invocation_closeout,
        "invocation_receipt_closeout_count": 1,
        "dry_run_invocation_readiness_receipt": receipt,
        "dry_run_invocation_readiness_receipt_count": 1,
        "apply_executor_readiness_closeout": readiness_closeout,
        "apply_executor_readiness_closeout_count": 1,
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": invocation_closeout.get("target_file"),
        "expected_sha256": invocation_closeout.get("expected_sha256"),
        "actual_sha256": invocation_closeout.get("actual_sha256"),
        "hash_matches": invocation_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "no_write_invocation_package_closeout_only": True,
        "execution_preflight_guard_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_no_write_invocation_package_closeout_contract = {
        "mode": "controlled_dry_run_no_write_invocation_package_closeout_and_execution_preflight_guard_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-write-invocation-package-closeout"
        ),
        "source_invocation_receipt_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-invocation-receipt-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_execution_preflight_guard": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_no_write_invocation_package_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_no_write_invocation_package_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_no_write_invocation_package_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_no_write_invocation_package_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_no_write_invocation_package_closeout_count": 1,
            "controlled_dry_run_no_write_invocation_package_closeout_field_count": len(
                package_closeout_fields
            ),
            "controlled_dry_run_no_write_invocation_package_closeout_acceptance_gate_count": len(
                package_closeout_acceptance_gates
            ),
            "execution_preflight_guard_count": 1,
            "execution_preflight_guard_field_count": len(
                execution_preflight_guard_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(invocation_closeout_result.get("success")),
        "generated_at": invocation_closeout_result.get("generated_at"),
        "source_policy": invocation_closeout_result.get("policy"),
        "stats": invocation_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_execution_preflight_guard": (
            future_database_apply_controlled_dry_run_execution_preflight_guard
        ),
        "controlled_dry_run_no_write_invocation_package_closeout": (
            controlled_dry_run_no_write_invocation_package_closeout
        ),
        "controlled_dry_run_no_write_invocation_package_closeout_contract": (
            controlled_dry_run_no_write_invocation_package_closeout_contract
        ),
        "controlled_dry_run_no_write_invocation_package_closeout_checks": checks,
        "source_controlled_dry_run_invocation_receipt_closeout_summary": summary,
        "source_controlled_dry_run_invocation_receipt_closeout_contract": (
            invocation_closeout_contract
        ),
        "source_controlled_dry_run_invocation_receipt_closeout": (
            invocation_closeout
        ),
        "source_database_apply_controlled_dry_run_no_write_invocation_package": (
            future_package
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_no_write_invocation_package_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run execution preflight guard closeout.",
            "Keep actual dry-run executor invocation disabled until the execution preflight guard is separately closed out.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the execution preflight guard and bind runner invocation boundary."""
    package_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_guard = (
        package_closeout_result.get(
            "future_database_apply_controlled_dry_run_execution_preflight_guard"
        )
        or {}
    )
    package_closeout = (
        package_closeout_result.get(
            "controlled_dry_run_no_write_invocation_package_closeout"
        )
        or {}
    )
    package_closeout_contract = (
        package_closeout_result.get(
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        )
        or {}
    )
    summary = package_closeout_result.get("summary") or {}
    safety = package_closeout_result.get("safety") or {}
    execution_preflight_guard = package_closeout.get("execution_preflight_guard") or {}
    package = package_closeout.get("no_write_invocation_package") or {}
    invocation_closeout = package_closeout.get("invocation_receipt_closeout") or {}
    receipt = (
        package_closeout.get("dry_run_invocation_readiness_receipt") or {}
    )
    readiness_closeout = (
        package_closeout.get("apply_executor_readiness_closeout") or {}
    )
    readiness_contract = (
        package_closeout.get("apply_executor_readiness_contract") or {}
    )
    pre_apply_closeout = package_closeout.get("pre_apply_replay_closeout") or {}
    replay_verifier = package_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = package_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        package_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = package_closeout.get("rollback_binding") or {}
    verifier_binding = package_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_execution_preflight_guard_closeout_id(
        package_closeout_result
    )
    boundary_id = f"{closeout_id}-runner-invocation-boundary"
    guard_closeout_fields = [
        "execution_preflight_guard_closeout_id",
        "source_no_write_invocation_package_closeout_id",
        "source_execution_preflight_guard_id",
        "source_no_write_invocation_package_id",
        "source_invocation_receipt_closeout_id",
        "required_command_shape_hash",
        "runner_invocation_boundary_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    guard_closeout_acceptance_gates = [
        "no_write_invocation_package_closeout_ready",
        "source_chain_ids_match",
        "execution_preflight_guard_ready",
        "execution_preflight_guard_no_execute",
        "runner_invocation_boundary_bound",
        "runner_invocation_boundary_blocks_execution",
        "no_write_package_and_invocation_receipt_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    runner_invocation_boundary_fields = [
        "boundary_id",
        "source_execution_preflight_guard_closeout_id",
        "source_execution_preflight_guard_id",
        "source_no_write_invocation_package_closeout_id",
        "source_no_write_invocation_package_id",
        "required_guard_mode",
        "required_command_shape_hash",
        "boundary_mode",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_no_write_invocation_package_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_execution_preflight_guard_missing",
        "abort_if_execution_preflight_guard_executes",
        "abort_if_runner_invocation_boundary_missing",
        "abort_if_runner_invocation_boundary_allows_invocation",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    runner_invocation_boundary = {
        "boundary_id": boundary_id,
        "source_execution_preflight_guard_closeout_id": closeout_id,
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "source_no_write_invocation_package_closeout_id": package_closeout.get(
            "no_write_invocation_package_closeout_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "source_invocation_receipt_closeout_id": invocation_closeout.get(
            "invocation_receipt_closeout_id"
        ),
        "required_guard_mode": "execution_preflight_guard_preview_only",
        "required_command_shape_hash": execution_preflight_guard.get(
            "required_command_shape_hash"
        ),
        "boundary_status": "runner_invocation_boundary_preview_ready",
        "boundary_mode": "runner_invocation_boundary_preview_only",
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_runner_invocation_boundary_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "reads_secret_in_preview": False,
        "runner_invocation_boundary_field_count": len(
            runner_invocation_boundary_fields
        ),
        "runner_invocation_boundary_fields": runner_invocation_boundary_fields,
    }
    package_closeout_ready = (
        package_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_no_write_invocation_package_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_no_write_invocation_package_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_no_write_invocation_package_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(package_closeout.get("no_write_invocation_package_closeout_id"))
        and package_closeout.get("no_write_invocation_package_closeout_id")
        == future_guard.get("no_write_invocation_package_closeout_id")
        == execution_preflight_guard.get(
            "source_no_write_invocation_package_closeout_id"
        )
        == runner_invocation_boundary.get(
            "source_no_write_invocation_package_closeout_id"
        )
        and execution_preflight_guard.get("guard_id")
        == future_guard.get("execution_preflight_guard_id")
        == runner_invocation_boundary.get(
            "source_execution_preflight_guard_id"
        )
        and package.get("package_id")
        == future_guard.get("source_no_write_invocation_package_id")
        == execution_preflight_guard.get(
            "source_no_write_invocation_package_id"
        )
        == runner_invocation_boundary.get(
            "source_no_write_invocation_package_id"
        )
        and invocation_closeout.get("invocation_receipt_closeout_id")
        == future_guard.get("source_invocation_receipt_closeout_id")
        == execution_preflight_guard.get("source_invocation_receipt_closeout_id")
        == runner_invocation_boundary.get("source_invocation_receipt_closeout_id")
    )
    execution_preflight_guard_ready = (
        execution_preflight_guard.get("guard_status")
        == "execution_preflight_guard_preview_ready"
        and execution_preflight_guard.get("guard_id")
        == future_guard.get("execution_preflight_guard_id")
        and int(
            execution_preflight_guard.get("execution_preflight_guard_field_count")
            or 0
        )
        == 12
    )
    execution_preflight_guard_no_execute = (
        execution_preflight_guard.get("guard_mode")
        == "execution_preflight_guard_preview_only"
        and execution_preflight_guard.get("dry_run_executor_invocation_allowed")
        is False
        and execution_preflight_guard.get("ready_for_execution_preflight_guard_now")
        is False
        and execution_preflight_guard.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and execution_preflight_guard.get("ready_for_actual_dry_run_execution_now")
        is False
        and execution_preflight_guard.get("endpoint_execution_allowed") is False
        and execution_preflight_guard.get("sql_execution_allowed") is False
        and execution_preflight_guard.get("database_write_allowed") is False
        and execution_preflight_guard.get("database_apply_authorized") is False
        and execution_preflight_guard.get("executes_database_apply") is False
        and execution_preflight_guard.get("executes_endpoint") is False
        and execution_preflight_guard.get("executes_sql") is False
        and execution_preflight_guard.get("writes_database") is False
    )
    runner_invocation_boundary_bound = (
        bool(runner_invocation_boundary.get("boundary_id"))
        and runner_invocation_boundary.get(
            "source_execution_preflight_guard_closeout_id"
        )
        == closeout_id
        and runner_invocation_boundary.get("source_execution_preflight_guard_id")
        == execution_preflight_guard.get("guard_id")
        and runner_invocation_boundary.get("required_command_shape_hash")
        == execution_preflight_guard.get("required_command_shape_hash")
        and int(
            runner_invocation_boundary.get(
                "runner_invocation_boundary_field_count"
            )
            or 0
        )
        == len(runner_invocation_boundary_fields)
    )
    runner_invocation_boundary_blocks_execution = (
        runner_invocation_boundary.get("boundary_mode")
        == "runner_invocation_boundary_preview_only"
        and runner_invocation_boundary.get("dry_run_executor_invocation_allowed")
        is False
        and runner_invocation_boundary.get("runner_invocation_allowed") is False
        and runner_invocation_boundary.get(
            "ready_for_runner_invocation_boundary_now"
        )
        is False
        and runner_invocation_boundary.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and runner_invocation_boundary.get("ready_for_actual_dry_run_execution_now")
        is False
        and runner_invocation_boundary.get("endpoint_execution_allowed") is False
        and runner_invocation_boundary.get("sql_execution_allowed") is False
        and runner_invocation_boundary.get("database_write_allowed") is False
        and runner_invocation_boundary.get("database_apply_authorized") is False
        and runner_invocation_boundary.get("executes_database_apply") is False
        and runner_invocation_boundary.get("executes_endpoint") is False
        and runner_invocation_boundary.get("executes_sql") is False
        and runner_invocation_boundary.get("writes_database") is False
        and runner_invocation_boundary.get("captures_stdout") is False
        and runner_invocation_boundary.get("captures_stderr") is False
    )
    no_write_package_and_invocation_receipt_carried_forward = (
        package.get("package_mode") == "no_write_invocation_package_preview_only"
        and package.get("dry_run_executor_invocation_allowed") is False
        and invocation_closeout.get("invocation_receipt_closeout_only") is True
        and invocation_closeout.get("database_apply_authorized") is False
        and receipt.get("receipt_mode") == "dry_run_invocation_readiness_preview_only"
        and receipt.get("dry_run_executor_invocation_allowed") is False
        and readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and readiness_contract.get("dry_run_executor_invocation_allowed")
        is False
        and replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and replay_verifier.get("database_apply_authorized") is False
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("dry_run_executor_invocation_allowed") is False
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("database_apply_authorized") is False
    )
    target_hash_locked = (
        package_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(package_closeout.get("expected_sha256"))
        and bool(package_closeout.get("actual_sha256"))
        and package_closeout.get("expected_sha256")
        == package_closeout.get("actual_sha256")
        and package_closeout.get("hash_matches") is True
        and package_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    package_closeout_contract_blocks_database_apply = (
        package_closeout_contract.get("executes_database_apply") is False
        and package_closeout_contract.get("executes_endpoint") is False
        and package_closeout_contract.get("executes_sql") is False
        and package_closeout_contract.get("database_apply_authorized") is False
        and package_closeout_contract.get("ready_for_database_apply_now")
        is False
        and package_closeout_contract.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and package_closeout_contract.get("ready_for_actual_dry_run_execution_now")
        is False
        and package_closeout_contract.get("signs_database_apply_authorization")
        is False
        and package_closeout_contract.get("writes_database") is False
        and package_closeout_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and execution_preflight_guard_no_execute
        and runner_invocation_boundary_blocks_execution
    )
    checks = [
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "no_write_invocation_package_closeout_ready",
            package_closeout_ready,
            {
                "result": package_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_no_write_invocation_package_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_no_write_invocation_package_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_no_write_invocation_package_closeout_check_count"
                ),
            },
            "wait_for_no_write_invocation_package_closeout_ready",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "no_write_invocation_package_closeout_id": package_closeout.get(
                    "no_write_invocation_package_closeout_id"
                ),
                "execution_preflight_guard_id": execution_preflight_guard.get(
                    "guard_id"
                ),
                "no_write_invocation_package_id": package.get("package_id"),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "execution_preflight_guard_ready",
            execution_preflight_guard_ready,
            {
                "guard_id": execution_preflight_guard.get("guard_id"),
                "guard_status": execution_preflight_guard.get("guard_status"),
                "field_count": execution_preflight_guard.get(
                    "execution_preflight_guard_field_count"
                ),
            },
            "wait_for_execution_preflight_guard_ready",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "execution_preflight_guard_no_execute",
            execution_preflight_guard_no_execute,
            {
                "guard_mode": execution_preflight_guard.get("guard_mode"),
                "dry_run_executor_invocation_allowed": (
                    execution_preflight_guard.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "ready_for_actual_dry_run_execution_now": (
                    execution_preflight_guard.get(
                        "ready_for_actual_dry_run_execution_now"
                    )
                ),
            },
            "abort_if_execution_preflight_guard_executes",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "runner_invocation_boundary_bound",
            runner_invocation_boundary_bound,
            {
                "boundary_id": runner_invocation_boundary.get("boundary_id"),
                "source_execution_preflight_guard_id": (
                    runner_invocation_boundary.get(
                        "source_execution_preflight_guard_id"
                    )
                ),
                "field_count": runner_invocation_boundary.get(
                    "runner_invocation_boundary_field_count"
                ),
            },
            "wait_for_runner_invocation_boundary_binding",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "runner_invocation_boundary_blocks_execution",
            runner_invocation_boundary_blocks_execution,
            {
                "boundary_mode": runner_invocation_boundary.get("boundary_mode"),
                "dry_run_executor_invocation_allowed": (
                    runner_invocation_boundary.get(
                        "dry_run_executor_invocation_allowed"
                    )
                ),
                "runner_invocation_allowed": runner_invocation_boundary.get(
                    "runner_invocation_allowed"
                ),
            },
            "abort_if_runner_invocation_boundary_allows_invocation",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "no_write_package_and_invocation_receipt_carried_forward",
            no_write_package_and_invocation_receipt_carried_forward,
            {
                "package_mode": package.get("package_mode"),
                "receipt_mode": receipt.get("receipt_mode"),
                "readiness_mode": readiness_contract.get("readiness_mode"),
            },
            "wait_for_no_write_package_and_invocation_receipt_carry_forward",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": package_closeout.get("target_file"),
                "hash_matches": package_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    package_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(
                    package_closeout.get("actual_sha256")
                ),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "no_write_invocation_package_closeout_contract_blocks_database_apply",
            package_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_execution_preflight_guard": (
                    package_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_execution_preflight_guard"
                    )
                ),
                "database_apply_authorized": package_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": package_closeout_contract.get(
                    "writes_database"
                ),
            },
            "abort_if_no_write_invocation_package_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_execution_preflight_guard_closeout_check(
            "manual_review_not_required_for_safe_preview",
            package_closeout_contract.get("manual_review_mode")
            == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": package_closeout_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_runner_invocation_boundary = {
        "execution_preflight_guard_closeout_id": closeout_id,
        "runner_invocation_boundary_id": boundary_id,
        "source_no_write_invocation_package_closeout_id": package_closeout.get(
            "no_write_invocation_package_closeout_id"
        ),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_runner_invocation_boundary": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_runner_invocation_boundary_closeout": (
            closeout_ready
        ),
        "execution_preflight_guard_closeout_ready": closeout_ready,
        "runner_invocation_boundary_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_execution_preflight_guard_closeout = {
        "execution_preflight_guard_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_execution_preflight_guard_closeout"
        ),
        "source_no_write_invocation_package_closeout_id": package_closeout.get(
            "no_write_invocation_package_closeout_id"
        ),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "source_invocation_receipt_closeout_id": invocation_closeout.get(
            "invocation_receipt_closeout_id"
        ),
        "required_command_shape_hash": execution_preflight_guard.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_preflight_guard_closeout": (
            closeout_ready
        ),
        "execution_preflight_guard_closeout_fields": guard_closeout_fields,
        "execution_preflight_guard_closeout_field_count": len(
            guard_closeout_fields
        ),
        "execution_preflight_guard_closeout_acceptance_gates": (
            guard_closeout_acceptance_gates
        ),
        "execution_preflight_guard_closeout_acceptance_gate_count": len(
            guard_closeout_acceptance_gates
        ),
        "runner_invocation_boundary": runner_invocation_boundary,
        "runner_invocation_boundary_count": 1,
        "runner_invocation_boundary_field_count": len(
            runner_invocation_boundary_fields
        ),
        "execution_preflight_guard": execution_preflight_guard,
        "execution_preflight_guard_count": 1,
        "no_write_invocation_package_closeout": package_closeout,
        "no_write_invocation_package_closeout_count": 1,
        "no_write_invocation_package": package,
        "no_write_invocation_package_count": 1,
        "invocation_receipt_closeout": invocation_closeout,
        "invocation_receipt_closeout_count": 1,
        "dry_run_invocation_readiness_receipt": receipt,
        "dry_run_invocation_readiness_receipt_count": 1,
        "apply_executor_readiness_closeout": readiness_closeout,
        "apply_executor_readiness_closeout_count": 1,
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": package_closeout.get("target_file"),
        "expected_sha256": package_closeout.get("expected_sha256"),
        "actual_sha256": package_closeout.get("actual_sha256"),
        "hash_matches": package_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "execution_preflight_guard_closeout_only": True,
        "runner_invocation_boundary_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
    }
    controlled_dry_run_execution_preflight_guard_closeout_contract = {
        "mode": "controlled_dry_run_execution_preflight_guard_closeout_and_runner_invocation_boundary_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-execution-preflight-guard-closeout"
        ),
        "source_no_write_invocation_package_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-write-invocation-package-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_runner_invocation_boundary": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_execution_preflight_guard_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_execution_preflight_guard_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_execution_preflight_guard_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_execution_preflight_guard_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_execution_preflight_guard_closeout_count": 1,
            "controlled_dry_run_execution_preflight_guard_closeout_field_count": len(
                guard_closeout_fields
            ),
            "controlled_dry_run_execution_preflight_guard_closeout_acceptance_gate_count": len(
                guard_closeout_acceptance_gates
            ),
            "runner_invocation_boundary_count": 1,
            "runner_invocation_boundary_field_count": len(
                runner_invocation_boundary_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(package_closeout_result.get("success")),
        "generated_at": package_closeout_result.get("generated_at"),
        "source_policy": package_closeout_result.get("policy"),
        "stats": package_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_runner_invocation_boundary": (
            future_database_apply_controlled_dry_run_runner_invocation_boundary
        ),
        "controlled_dry_run_execution_preflight_guard_closeout": (
            controlled_dry_run_execution_preflight_guard_closeout
        ),
        "controlled_dry_run_execution_preflight_guard_closeout_contract": (
            controlled_dry_run_execution_preflight_guard_closeout_contract
        ),
        "controlled_dry_run_execution_preflight_guard_closeout_checks": checks,
        "source_controlled_dry_run_no_write_invocation_package_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_no_write_invocation_package_closeout_contract": (
            package_closeout_contract
        ),
        "source_controlled_dry_run_no_write_invocation_package_closeout": (
            package_closeout
        ),
        "source_database_apply_controlled_dry_run_execution_preflight_guard": (
            future_guard
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_execution_preflight_guard_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run runner invocation boundary closeout.",
            "Keep actual runner invocation disabled until the boundary closeout is separately machine-verifiable.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out runner invocation boundary and bind no-execution handoff."""
    guard_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_boundary = (
        guard_closeout_result.get(
            "future_database_apply_controlled_dry_run_runner_invocation_boundary"
        )
        or {}
    )
    guard_closeout = (
        guard_closeout_result.get(
            "controlled_dry_run_execution_preflight_guard_closeout"
        )
        or {}
    )
    guard_closeout_contract = (
        guard_closeout_result.get(
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        )
        or {}
    )
    summary = guard_closeout_result.get("summary") or {}
    safety = guard_closeout_result.get("safety") or {}
    boundary = guard_closeout.get("runner_invocation_boundary") or {}
    execution_preflight_guard = guard_closeout.get("execution_preflight_guard") or {}
    package_closeout = guard_closeout.get("no_write_invocation_package_closeout") or {}
    package = guard_closeout.get("no_write_invocation_package") or {}
    invocation_closeout = guard_closeout.get("invocation_receipt_closeout") or {}
    receipt = guard_closeout.get("dry_run_invocation_readiness_receipt") or {}
    readiness_closeout = guard_closeout.get("apply_executor_readiness_closeout") or {}
    readiness_contract = guard_closeout.get("apply_executor_readiness_contract") or {}
    pre_apply_closeout = guard_closeout.get("pre_apply_replay_closeout") or {}
    replay_verifier = guard_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = guard_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        guard_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = guard_closeout.get("rollback_binding") or {}
    verifier_binding = guard_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = _db_apply_controlled_dry_run_runner_invocation_boundary_closeout_id(
        guard_closeout_result
    )
    handoff_id = f"{closeout_id}-no-execution-receipt-handoff"
    boundary_closeout_fields = [
        "runner_invocation_boundary_closeout_id",
        "source_execution_preflight_guard_closeout_id",
        "source_runner_invocation_boundary_id",
        "source_execution_preflight_guard_id",
        "source_no_write_invocation_package_id",
        "required_command_shape_hash",
        "no_execution_receipt_handoff_id",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    boundary_closeout_acceptance_gates = [
        "execution_preflight_guard_closeout_ready",
        "source_chain_ids_match",
        "runner_invocation_boundary_ready",
        "runner_invocation_boundary_no_execute",
        "no_execution_receipt_handoff_bound",
        "no_execution_receipt_handoff_blocks_execution",
        "execution_preflight_guard_and_no_write_package_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    no_execution_receipt_handoff_fields = [
        "handoff_id",
        "source_runner_invocation_boundary_closeout_id",
        "source_runner_invocation_boundary_id",
        "source_execution_preflight_guard_closeout_id",
        "source_execution_preflight_guard_id",
        "required_boundary_mode",
        "required_command_shape_hash",
        "handoff_mode",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_execution_preflight_guard_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_runner_invocation_boundary_missing",
        "abort_if_runner_invocation_boundary_allows_invocation",
        "abort_if_no_execution_receipt_handoff_missing",
        "abort_if_no_execution_receipt_handoff_executes",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    no_execution_receipt_handoff = {
        "handoff_id": handoff_id,
        "source_runner_invocation_boundary_closeout_id": closeout_id,
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "required_boundary_mode": "runner_invocation_boundary_preview_only",
        "required_command_shape_hash": boundary.get("required_command_shape_hash"),
        "handoff_status": "no_execution_receipt_handoff_preview_ready",
        "handoff_mode": "no_execution_receipt_handoff_preview_only",
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_no_execution_receipt_handoff_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "no_execution_receipt_handoff_field_count": len(
            no_execution_receipt_handoff_fields
        ),
        "no_execution_receipt_handoff_fields": no_execution_receipt_handoff_fields,
    }
    guard_closeout_ready = (
        guard_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_execution_preflight_guard_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_execution_preflight_guard_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_execution_preflight_guard_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(guard_closeout.get("execution_preflight_guard_closeout_id"))
        and guard_closeout.get("execution_preflight_guard_closeout_id")
        == future_boundary.get("execution_preflight_guard_closeout_id")
        == boundary.get("source_execution_preflight_guard_closeout_id")
        == no_execution_receipt_handoff.get(
            "source_execution_preflight_guard_closeout_id"
        )
        and boundary.get("boundary_id")
        == future_boundary.get("runner_invocation_boundary_id")
        == no_execution_receipt_handoff.get(
            "source_runner_invocation_boundary_id"
        )
        and execution_preflight_guard.get("guard_id")
        == future_boundary.get("source_execution_preflight_guard_id")
        == boundary.get("source_execution_preflight_guard_id")
        == no_execution_receipt_handoff.get(
            "source_execution_preflight_guard_id"
        )
        and package.get("package_id")
        == future_boundary.get("source_no_write_invocation_package_id")
        == boundary.get("source_no_write_invocation_package_id")
        == no_execution_receipt_handoff.get(
            "source_no_write_invocation_package_id"
        )
    )
    runner_invocation_boundary_ready = (
        boundary.get("boundary_status")
        == "runner_invocation_boundary_preview_ready"
        and boundary.get("boundary_id")
        == future_boundary.get("runner_invocation_boundary_id")
        and int(boundary.get("runner_invocation_boundary_field_count") or 0)
        == 12
    )
    runner_invocation_boundary_no_execute = (
        boundary.get("boundary_mode") == "runner_invocation_boundary_preview_only"
        and boundary.get("dry_run_executor_invocation_allowed") is False
        and boundary.get("runner_invocation_allowed") is False
        and boundary.get("ready_for_runner_invocation_boundary_now") is False
        and boundary.get("ready_for_dry_run_executor_invocation_now") is False
        and boundary.get("ready_for_actual_dry_run_execution_now") is False
        and boundary.get("endpoint_execution_allowed") is False
        and boundary.get("sql_execution_allowed") is False
        and boundary.get("database_write_allowed") is False
        and boundary.get("database_apply_authorized") is False
        and boundary.get("executes_database_apply") is False
        and boundary.get("executes_endpoint") is False
        and boundary.get("executes_sql") is False
        and boundary.get("writes_database") is False
        and boundary.get("captures_stdout") is False
        and boundary.get("captures_stderr") is False
    )
    no_execution_receipt_handoff_bound = (
        bool(no_execution_receipt_handoff.get("handoff_id"))
        and no_execution_receipt_handoff.get(
            "source_runner_invocation_boundary_closeout_id"
        )
        == closeout_id
        and no_execution_receipt_handoff.get(
            "source_runner_invocation_boundary_id"
        )
        == boundary.get("boundary_id")
        and no_execution_receipt_handoff.get("required_command_shape_hash")
        == boundary.get("required_command_shape_hash")
        and int(
            no_execution_receipt_handoff.get(
                "no_execution_receipt_handoff_field_count"
            )
            or 0
        )
        == len(no_execution_receipt_handoff_fields)
    )
    no_execution_receipt_handoff_blocks_execution = (
        no_execution_receipt_handoff.get("handoff_mode")
        == "no_execution_receipt_handoff_preview_only"
        and no_execution_receipt_handoff.get("execution_receipt_present") is False
        and no_execution_receipt_handoff.get("execution_receipt_required") is False
        and no_execution_receipt_handoff.get("dry_run_executor_invocation_allowed")
        is False
        and no_execution_receipt_handoff.get("runner_invocation_allowed") is False
        and no_execution_receipt_handoff.get(
            "ready_for_no_execution_receipt_handoff_now"
        )
        is False
        and no_execution_receipt_handoff.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and no_execution_receipt_handoff.get("ready_for_actual_dry_run_execution_now")
        is False
        and no_execution_receipt_handoff.get("endpoint_execution_allowed") is False
        and no_execution_receipt_handoff.get("sql_execution_allowed") is False
        and no_execution_receipt_handoff.get("database_write_allowed") is False
        and no_execution_receipt_handoff.get("database_apply_authorized") is False
        and no_execution_receipt_handoff.get("executes_database_apply") is False
        and no_execution_receipt_handoff.get("executes_endpoint") is False
        and no_execution_receipt_handoff.get("executes_sql") is False
        and no_execution_receipt_handoff.get("writes_database") is False
        and no_execution_receipt_handoff.get("captures_stdout") is False
        and no_execution_receipt_handoff.get("captures_stderr") is False
        and no_execution_receipt_handoff.get("stdout_included") is False
        and no_execution_receipt_handoff.get("stderr_included") is False
    )
    execution_preflight_guard_and_no_write_package_carried_forward = (
        execution_preflight_guard.get("guard_mode")
        == "execution_preflight_guard_preview_only"
        and execution_preflight_guard.get("dry_run_executor_invocation_allowed")
        is False
        and guard_closeout.get("execution_preflight_guard_closeout_only") is True
        and package_closeout.get("no_write_invocation_package_closeout_only") is True
        and package_closeout.get("database_apply_authorized") is False
        and package.get("package_mode") == "no_write_invocation_package_preview_only"
        and package.get("dry_run_executor_invocation_allowed") is False
        and invocation_closeout.get("invocation_receipt_closeout_only") is True
        and invocation_closeout.get("database_apply_authorized") is False
        and receipt.get("receipt_mode") == "dry_run_invocation_readiness_preview_only"
        and receipt.get("dry_run_executor_invocation_allowed") is False
        and readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and readiness_contract.get("dry_run_executor_invocation_allowed")
        is False
        and replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and replay_verifier.get("database_apply_authorized") is False
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and final_guard.get("dry_run_executor_invocation_allowed") is False
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_apply_enforcement.get("database_apply_authorized") is False
    )
    target_hash_locked = (
        guard_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(guard_closeout.get("expected_sha256"))
        and bool(guard_closeout.get("actual_sha256"))
        and guard_closeout.get("expected_sha256")
        == guard_closeout.get("actual_sha256")
        and guard_closeout.get("hash_matches") is True
        and guard_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    guard_closeout_contract_blocks_database_apply = (
        guard_closeout_contract.get("executes_database_apply") is False
        and guard_closeout_contract.get("executes_endpoint") is False
        and guard_closeout_contract.get("executes_sql") is False
        and guard_closeout_contract.get("database_apply_authorized") is False
        and guard_closeout_contract.get("ready_for_database_apply_now") is False
        and guard_closeout_contract.get("ready_for_dry_run_executor_invocation_now")
        is False
        and guard_closeout_contract.get("ready_for_actual_dry_run_execution_now")
        is False
        and guard_closeout_contract.get("signs_database_apply_authorization")
        is False
        and guard_closeout_contract.get("writes_database") is False
        and guard_closeout_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and runner_invocation_boundary_no_execute
        and no_execution_receipt_handoff_blocks_execution
    )
    checks = [
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "execution_preflight_guard_closeout_ready",
            guard_closeout_ready,
            {
                "result": guard_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_execution_preflight_guard_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_execution_preflight_guard_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_execution_preflight_guard_closeout_check_count"
                ),
            },
            "wait_for_execution_preflight_guard_closeout_ready",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "execution_preflight_guard_closeout_id": guard_closeout.get(
                    "execution_preflight_guard_closeout_id"
                ),
                "runner_invocation_boundary_id": boundary.get("boundary_id"),
                "execution_preflight_guard_id": execution_preflight_guard.get(
                    "guard_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "runner_invocation_boundary_ready",
            runner_invocation_boundary_ready,
            {
                "boundary_id": boundary.get("boundary_id"),
                "boundary_status": boundary.get("boundary_status"),
                "field_count": boundary.get(
                    "runner_invocation_boundary_field_count"
                ),
            },
            "wait_for_runner_invocation_boundary_ready",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "runner_invocation_boundary_no_execute",
            runner_invocation_boundary_no_execute,
            {
                "boundary_mode": boundary.get("boundary_mode"),
                "dry_run_executor_invocation_allowed": boundary.get(
                    "dry_run_executor_invocation_allowed"
                ),
                "runner_invocation_allowed": boundary.get(
                    "runner_invocation_allowed"
                ),
            },
            "abort_if_runner_invocation_boundary_allows_invocation",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "no_execution_receipt_handoff_bound",
            no_execution_receipt_handoff_bound,
            {
                "handoff_id": no_execution_receipt_handoff.get("handoff_id"),
                "source_runner_invocation_boundary_id": (
                    no_execution_receipt_handoff.get(
                        "source_runner_invocation_boundary_id"
                    )
                ),
                "field_count": no_execution_receipt_handoff.get(
                    "no_execution_receipt_handoff_field_count"
                ),
            },
            "wait_for_no_execution_receipt_handoff_binding",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "no_execution_receipt_handoff_blocks_execution",
            no_execution_receipt_handoff_blocks_execution,
            {
                "handoff_mode": no_execution_receipt_handoff.get("handoff_mode"),
                "execution_receipt_present": no_execution_receipt_handoff.get(
                    "execution_receipt_present"
                ),
                "runner_invocation_allowed": no_execution_receipt_handoff.get(
                    "runner_invocation_allowed"
                ),
            },
            "abort_if_no_execution_receipt_handoff_executes",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "execution_preflight_guard_and_no_write_package_carried_forward",
            execution_preflight_guard_and_no_write_package_carried_forward,
            {
                "guard_closeout_only": guard_closeout.get(
                    "execution_preflight_guard_closeout_only"
                ),
                "package_closeout_only": package_closeout.get(
                    "no_write_invocation_package_closeout_only"
                ),
                "guard_mode": execution_preflight_guard.get("guard_mode"),
                "package_mode": package.get("package_mode"),
                "receipt_mode": receipt.get("receipt_mode"),
            },
            "wait_for_execution_preflight_guard_and_no_write_package_carry_forward",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": guard_closeout.get("target_file"),
                "hash_matches": guard_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    guard_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(
                    guard_closeout.get("actual_sha256")
                ),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "execution_preflight_guard_closeout_contract_blocks_database_apply",
            guard_closeout_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_runner_invocation_boundary": (
                    guard_closeout_contract.get(
                        "permits_future_database_apply_controlled_dry_run_runner_invocation_boundary"
                    )
                ),
                "database_apply_authorized": guard_closeout_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": guard_closeout_contract.get("writes_database"),
            },
            "abort_if_execution_preflight_guard_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_runner_invocation_boundary_closeout_check(
            "manual_review_not_required_for_safe_preview",
            guard_closeout_contract.get("manual_review_mode")
            == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": guard_closeout_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_no_execution_receipt_handoff = {
        "runner_invocation_boundary_closeout_id": closeout_id,
        "no_execution_receipt_handoff_id": handoff_id,
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_execution_receipt_handoff": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_no_execution_receipt_handoff_closeout": (
            closeout_ready
        ),
        "runner_invocation_boundary_closeout_ready": closeout_ready,
        "no_execution_receipt_handoff_bound": closeout_ready,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "execution_receipt_present": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_runner_invocation_boundary_closeout = {
        "runner_invocation_boundary_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_runner_invocation_boundary_closeout"
        ),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "source_no_write_invocation_package_id": package.get("package_id"),
        "required_command_shape_hash": boundary.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_runner_invocation_boundary_closeout": (
            closeout_ready
        ),
        "runner_invocation_boundary_closeout_fields": boundary_closeout_fields,
        "runner_invocation_boundary_closeout_field_count": len(
            boundary_closeout_fields
        ),
        "runner_invocation_boundary_closeout_acceptance_gates": (
            boundary_closeout_acceptance_gates
        ),
        "runner_invocation_boundary_closeout_acceptance_gate_count": len(
            boundary_closeout_acceptance_gates
        ),
        "no_execution_receipt_handoff": no_execution_receipt_handoff,
        "no_execution_receipt_handoff_count": 1,
        "no_execution_receipt_handoff_field_count": len(
            no_execution_receipt_handoff_fields
        ),
        "runner_invocation_boundary": boundary,
        "runner_invocation_boundary_count": 1,
        "execution_preflight_guard_closeout": guard_closeout,
        "execution_preflight_guard_closeout_count": 1,
        "execution_preflight_guard": execution_preflight_guard,
        "execution_preflight_guard_count": 1,
        "no_write_invocation_package_closeout": package_closeout,
        "no_write_invocation_package_closeout_count": 1,
        "no_write_invocation_package": package,
        "no_write_invocation_package_count": 1,
        "invocation_receipt_closeout": invocation_closeout,
        "invocation_receipt_closeout_count": 1,
        "dry_run_invocation_readiness_receipt": receipt,
        "dry_run_invocation_readiness_receipt_count": 1,
        "apply_executor_readiness_closeout": readiness_closeout,
        "apply_executor_readiness_closeout_count": 1,
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": guard_closeout.get("target_file"),
        "expected_sha256": guard_closeout.get("expected_sha256"),
        "actual_sha256": guard_closeout.get("actual_sha256"),
        "hash_matches": guard_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "runner_invocation_boundary_closeout_only": True,
        "no_execution_receipt_handoff_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
    }
    controlled_dry_run_runner_invocation_boundary_closeout_contract = {
        "mode": "controlled_dry_run_runner_invocation_boundary_closeout_and_no_execution_receipt_handoff_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-runner-invocation-boundary-closeout"
        ),
        "source_execution_preflight_guard_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-execution-preflight-guard-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_no_execution_receipt_handoff": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_runner_invocation_boundary_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_runner_invocation_boundary_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_runner_invocation_boundary_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_runner_invocation_boundary_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_runner_invocation_boundary_closeout_count": 1,
            "controlled_dry_run_runner_invocation_boundary_closeout_field_count": len(
                boundary_closeout_fields
            ),
            "controlled_dry_run_runner_invocation_boundary_closeout_acceptance_gate_count": len(
                boundary_closeout_acceptance_gates
            ),
            "no_execution_receipt_handoff_count": 1,
            "no_execution_receipt_handoff_field_count": len(
                no_execution_receipt_handoff_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(guard_closeout_result.get("success")),
        "generated_at": guard_closeout_result.get("generated_at"),
        "source_policy": guard_closeout_result.get("policy"),
        "stats": guard_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_no_execution_receipt_handoff": (
            future_database_apply_controlled_dry_run_no_execution_receipt_handoff
        ),
        "controlled_dry_run_runner_invocation_boundary_closeout": (
            controlled_dry_run_runner_invocation_boundary_closeout
        ),
        "controlled_dry_run_runner_invocation_boundary_closeout_contract": (
            controlled_dry_run_runner_invocation_boundary_closeout_contract
        ),
        "controlled_dry_run_runner_invocation_boundary_closeout_checks": checks,
        "source_controlled_dry_run_execution_preflight_guard_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_execution_preflight_guard_closeout_contract": (
            guard_closeout_contract
        ),
        "source_controlled_dry_run_execution_preflight_guard_closeout": (
            guard_closeout
        ),
        "source_database_apply_controlled_dry_run_runner_invocation_boundary": (
            future_boundary
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_runner_invocation_boundary_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled dry-run no-execution receipt handoff closeout.",
            "Keep actual runner invocation disabled until an execution receipt is separately authorized outside this preview lane.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out no-execution handoff and bind final no-runner proof."""
    boundary_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_handoff = (
        boundary_closeout_result.get(
            "future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
        )
        or {}
    )
    boundary_closeout = (
        boundary_closeout_result.get(
            "controlled_dry_run_runner_invocation_boundary_closeout"
        )
        or {}
    )
    boundary_contract = (
        boundary_closeout_result.get(
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        )
        or {}
    )
    summary = boundary_closeout_result.get("summary") or {}
    safety = boundary_closeout_result.get("safety") or {}
    handoff = boundary_closeout.get("no_execution_receipt_handoff") or {}
    boundary = boundary_closeout.get("runner_invocation_boundary") or {}
    guard_closeout = boundary_closeout.get("execution_preflight_guard_closeout") or {}
    execution_preflight_guard = boundary_closeout.get("execution_preflight_guard") or {}
    package_closeout = boundary_closeout.get("no_write_invocation_package_closeout") or {}
    package = boundary_closeout.get("no_write_invocation_package") or {}
    invocation_closeout = boundary_closeout.get("invocation_receipt_closeout") or {}
    receipt = boundary_closeout.get("dry_run_invocation_readiness_receipt") or {}
    readiness_closeout = boundary_closeout.get("apply_executor_readiness_closeout") or {}
    readiness_contract = boundary_closeout.get("apply_executor_readiness_contract") or {}
    pre_apply_closeout = boundary_closeout.get("pre_apply_replay_closeout") or {}
    replay_verifier = boundary_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = boundary_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        boundary_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = boundary_closeout.get("rollback_binding") or {}
    verifier_binding = boundary_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = (
        _db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout_id(
            boundary_closeout_result
        )
    )
    proof_id = f"{closeout_id}-final-no-runner-execution-proof"
    handoff_closeout_fields = [
        "no_execution_receipt_handoff_closeout_id",
        "source_runner_invocation_boundary_closeout_id",
        "source_no_execution_receipt_handoff_id",
        "source_runner_invocation_boundary_id",
        "source_execution_preflight_guard_closeout_id",
        "final_no_runner_execution_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    handoff_closeout_acceptance_gates = [
        "runner_invocation_boundary_closeout_ready",
        "source_chain_ids_match",
        "no_execution_receipt_handoff_ready",
        "no_execution_receipt_handoff_no_execute",
        "final_no_runner_execution_proof_bound",
        "final_no_runner_execution_proof_blocks_execution",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    final_no_runner_execution_proof_fields = [
        "proof_id",
        "source_no_execution_receipt_handoff_closeout_id",
        "source_no_execution_receipt_handoff_id",
        "source_runner_invocation_boundary_closeout_id",
        "source_runner_invocation_boundary_id",
        "source_execution_preflight_guard_closeout_id",
        "proof_mode",
        "dry_run_executor_invocation_allowed",
        "runner_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_runner_invocation_boundary_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_no_execution_receipt_handoff_missing",
        "abort_if_no_execution_receipt_handoff_allows_execution",
        "abort_if_final_no_runner_execution_proof_missing",
        "abort_if_final_no_runner_execution_proof_reports_execution",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    final_no_runner_execution_proof = {
        "proof_id": proof_id,
        "source_no_execution_receipt_handoff_closeout_id": closeout_id,
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "required_handoff_mode": "no_execution_receipt_handoff_preview_only",
        "required_command_shape_hash": handoff.get("required_command_shape_hash"),
        "proof_status": "final_no_runner_execution_proof_preview_ready",
        "proof_mode": "final_no_runner_execution_proof_preview_only",
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_final_no_runner_execution_proof_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "final_no_runner_execution_proof_field_count": len(
            final_no_runner_execution_proof_fields
        ),
        "final_no_runner_execution_proof_fields": (
            final_no_runner_execution_proof_fields
        ),
    }
    boundary_closeout_ready = (
        boundary_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_runner_invocation_boundary_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_runner_invocation_boundary_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_runner_invocation_boundary_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(boundary_closeout.get("runner_invocation_boundary_closeout_id"))
        and boundary_closeout.get("runner_invocation_boundary_closeout_id")
        == future_handoff.get("runner_invocation_boundary_closeout_id")
        == handoff.get("source_runner_invocation_boundary_closeout_id")
        == final_no_runner_execution_proof.get(
            "source_runner_invocation_boundary_closeout_id"
        )
        and handoff.get("handoff_id")
        == future_handoff.get("no_execution_receipt_handoff_id")
        == final_no_runner_execution_proof.get(
            "source_no_execution_receipt_handoff_id"
        )
        and boundary.get("boundary_id")
        == future_handoff.get("source_runner_invocation_boundary_id")
        == handoff.get("source_runner_invocation_boundary_id")
        == final_no_runner_execution_proof.get(
            "source_runner_invocation_boundary_id"
        )
        and guard_closeout.get("execution_preflight_guard_closeout_id")
        == future_handoff.get("source_execution_preflight_guard_closeout_id")
        == handoff.get("source_execution_preflight_guard_closeout_id")
        == final_no_runner_execution_proof.get(
            "source_execution_preflight_guard_closeout_id"
        )
        and execution_preflight_guard.get("guard_id")
        == future_handoff.get("source_execution_preflight_guard_id")
        == handoff.get("source_execution_preflight_guard_id")
        == final_no_runner_execution_proof.get("source_execution_preflight_guard_id")
    )
    no_execution_receipt_handoff_ready = (
        handoff.get("handoff_status") == "no_execution_receipt_handoff_preview_ready"
        and handoff.get("handoff_id")
        == future_handoff.get("no_execution_receipt_handoff_id")
        and int(handoff.get("no_execution_receipt_handoff_field_count") or 0)
        == 12
        and summary.get("no_execution_receipt_handoff_count") == 1
    )
    no_execution_receipt_handoff_no_execute = (
        handoff.get("handoff_mode") == "no_execution_receipt_handoff_preview_only"
        and handoff.get("execution_receipt_present") is False
        and handoff.get("execution_receipt_required") is False
        and handoff.get("dry_run_executor_invocation_allowed") is False
        and handoff.get("runner_invocation_allowed") is False
        and handoff.get("ready_for_no_execution_receipt_handoff_now") is False
        and handoff.get("ready_for_dry_run_executor_invocation_now") is False
        and handoff.get("ready_for_actual_dry_run_execution_now") is False
        and handoff.get("endpoint_execution_allowed") is False
        and handoff.get("sql_execution_allowed") is False
        and handoff.get("database_write_allowed") is False
        and handoff.get("database_apply_authorized") is False
        and handoff.get("executes_database_apply") is False
        and handoff.get("executes_endpoint") is False
        and handoff.get("executes_sql") is False
        and handoff.get("writes_database") is False
        and handoff.get("captures_stdout") is False
        and handoff.get("captures_stderr") is False
        and handoff.get("stdout_included") is False
        and handoff.get("stderr_included") is False
    )
    final_no_runner_execution_proof_bound = (
        bool(final_no_runner_execution_proof.get("proof_id"))
        and final_no_runner_execution_proof.get(
            "source_no_execution_receipt_handoff_closeout_id"
        )
        == closeout_id
        and final_no_runner_execution_proof.get(
            "source_no_execution_receipt_handoff_id"
        )
        == handoff.get("handoff_id")
        and final_no_runner_execution_proof.get("required_command_shape_hash")
        == handoff.get("required_command_shape_hash")
        and int(
            final_no_runner_execution_proof.get(
                "final_no_runner_execution_proof_field_count"
            )
            or 0
        )
        == len(final_no_runner_execution_proof_fields)
    )
    final_no_runner_execution_proof_blocks_execution = (
        final_no_runner_execution_proof.get("proof_mode")
        == "final_no_runner_execution_proof_preview_only"
        and final_no_runner_execution_proof.get("execution_receipt_present")
        is False
        and final_no_runner_execution_proof.get("execution_receipt_required")
        is False
        and final_no_runner_execution_proof.get("dry_run_executor_invoked")
        is False
        and final_no_runner_execution_proof.get("runner_invocation_performed")
        is False
        and final_no_runner_execution_proof.get("endpoint_executed") is False
        and final_no_runner_execution_proof.get("sql_executed") is False
        and final_no_runner_execution_proof.get("database_written") is False
        and final_no_runner_execution_proof.get(
            "dry_run_executor_invocation_allowed"
        )
        is False
        and final_no_runner_execution_proof.get("runner_invocation_allowed")
        is False
        and final_no_runner_execution_proof.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and final_no_runner_execution_proof.get(
            "ready_for_actual_dry_run_execution_now"
        )
        is False
        and final_no_runner_execution_proof.get("endpoint_execution_allowed")
        is False
        and final_no_runner_execution_proof.get("sql_execution_allowed") is False
        and final_no_runner_execution_proof.get("database_write_allowed") is False
        and final_no_runner_execution_proof.get("database_apply_authorized")
        is False
        and final_no_runner_execution_proof.get("executes_database_apply")
        is False
        and final_no_runner_execution_proof.get("executes_endpoint") is False
        and final_no_runner_execution_proof.get("executes_sql") is False
        and final_no_runner_execution_proof.get("writes_database") is False
        and final_no_runner_execution_proof.get("captures_stdout") is False
        and final_no_runner_execution_proof.get("captures_stderr") is False
        and final_no_runner_execution_proof.get("stdout_included") is False
        and final_no_runner_execution_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        boundary_closeout.get("runner_invocation_boundary_closeout_only") is True
        and boundary_closeout.get("no_execution_receipt_handoff_only") is True
        and boundary_closeout.get("database_apply_authorized") is False
        and guard_closeout.get("execution_preflight_guard_closeout_only") is True
        and package_closeout.get("no_write_invocation_package_closeout_only")
        is True
        and package.get("package_mode") == "no_write_invocation_package_preview_only"
        and invocation_closeout.get("invocation_receipt_closeout_only") is True
        and receipt.get("receipt_mode") == "dry_run_invocation_readiness_preview_only"
        and readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and no_execution_receipt_handoff_no_execute
    )
    target_hash_locked = (
        boundary_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(boundary_closeout.get("expected_sha256"))
        and bool(boundary_closeout.get("actual_sha256"))
        and boundary_closeout.get("expected_sha256")
        == boundary_closeout.get("actual_sha256")
        and boundary_closeout.get("hash_matches") is True
        and boundary_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    boundary_contract_blocks_database_apply = (
        boundary_contract.get("executes_database_apply") is False
        and boundary_contract.get("executes_endpoint") is False
        and boundary_contract.get("executes_sql") is False
        and boundary_contract.get("database_apply_authorized") is False
        and boundary_contract.get("ready_for_database_apply_now") is False
        and boundary_contract.get("ready_for_dry_run_executor_invocation_now")
        is False
        and boundary_contract.get("ready_for_actual_dry_run_execution_now")
        is False
        and boundary_contract.get("signs_database_apply_authorization") is False
        and boundary_contract.get("writes_database") is False
        and boundary_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and no_execution_receipt_handoff_no_execute
        and final_no_runner_execution_proof_blocks_execution
    )
    checks = [
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "runner_invocation_boundary_closeout_ready",
            boundary_closeout_ready,
            {
                "result": boundary_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_runner_invocation_boundary_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_runner_invocation_boundary_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_runner_invocation_boundary_closeout_check_count"
                ),
            },
            "wait_for_runner_invocation_boundary_closeout_ready",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "runner_invocation_boundary_closeout_id": boundary_closeout.get(
                    "runner_invocation_boundary_closeout_id"
                ),
                "no_execution_receipt_handoff_id": handoff.get("handoff_id"),
                "proof_id": final_no_runner_execution_proof.get("proof_id"),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "no_execution_receipt_handoff_ready",
            no_execution_receipt_handoff_ready,
            {
                "handoff_id": handoff.get("handoff_id"),
                "handoff_status": handoff.get("handoff_status"),
                "field_count": handoff.get("no_execution_receipt_handoff_field_count"),
            },
            "wait_for_no_execution_receipt_handoff_ready",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "no_execution_receipt_handoff_no_execute",
            no_execution_receipt_handoff_no_execute,
            {
                "handoff_mode": handoff.get("handoff_mode"),
                "execution_receipt_present": handoff.get("execution_receipt_present"),
                "runner_invocation_allowed": handoff.get("runner_invocation_allowed"),
            },
            "abort_if_no_execution_receipt_handoff_executes",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "final_no_runner_execution_proof_bound",
            final_no_runner_execution_proof_bound,
            {
                "proof_id": final_no_runner_execution_proof.get("proof_id"),
                "source_no_execution_receipt_handoff_id": (
                    final_no_runner_execution_proof.get(
                        "source_no_execution_receipt_handoff_id"
                    )
                ),
                "field_count": final_no_runner_execution_proof.get(
                    "final_no_runner_execution_proof_field_count"
                ),
            },
            "wait_for_final_no_runner_execution_proof_binding",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "final_no_runner_execution_proof_blocks_execution",
            final_no_runner_execution_proof_blocks_execution,
            {
                "proof_mode": final_no_runner_execution_proof.get("proof_mode"),
                "dry_run_executor_invoked": final_no_runner_execution_proof.get(
                    "dry_run_executor_invoked"
                ),
                "runner_invocation_performed": final_no_runner_execution_proof.get(
                    "runner_invocation_performed"
                ),
            },
            "abort_if_final_no_runner_execution_proof_reports_execution",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "runner_invocation_boundary_closeout_only": boundary_closeout.get(
                    "runner_invocation_boundary_closeout_only"
                ),
                "no_execution_receipt_handoff_only": boundary_closeout.get(
                    "no_execution_receipt_handoff_only"
                ),
                "handoff_mode": handoff.get("handoff_mode"),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": boundary_closeout.get("target_file"),
                "hash_matches": boundary_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    boundary_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(boundary_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "runner_invocation_boundary_closeout_contract_blocks_database_apply",
            boundary_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_no_execution_receipt_handoff": (
                    boundary_contract.get(
                        "permits_future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
                    )
                ),
                "database_apply_authorized": boundary_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": boundary_contract.get("writes_database"),
            },
            "abort_if_runner_invocation_boundary_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_no_execution_receipt_handoff_closeout_check(
            "manual_review_not_required_for_safe_preview",
            boundary_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": boundary_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_final_no_runner_execution_proof = {
        "no_execution_receipt_handoff_closeout_id": closeout_id,
        "final_no_runner_execution_proof_id": proof_id,
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_final_no_runner_execution_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_final_no_runner_execution_proof_closeout": (
            closeout_ready
        ),
        "no_execution_receipt_handoff_closeout_ready": closeout_ready,
        "final_no_runner_execution_proof_bound": closeout_ready,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_no_execution_receipt_handoff_closeout = {
        "no_execution_receipt_handoff_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_no_execution_receipt_handoff_closeout"
        ),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "source_execution_preflight_guard_id": execution_preflight_guard.get(
            "guard_id"
        ),
        "required_command_shape_hash": handoff.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_execution_receipt_handoff_closeout": (
            closeout_ready
        ),
        "no_execution_receipt_handoff_closeout_fields": handoff_closeout_fields,
        "no_execution_receipt_handoff_closeout_field_count": len(
            handoff_closeout_fields
        ),
        "no_execution_receipt_handoff_closeout_acceptance_gates": (
            handoff_closeout_acceptance_gates
        ),
        "no_execution_receipt_handoff_closeout_acceptance_gate_count": len(
            handoff_closeout_acceptance_gates
        ),
        "final_no_runner_execution_proof": final_no_runner_execution_proof,
        "final_no_runner_execution_proof_count": 1,
        "final_no_runner_execution_proof_field_count": len(
            final_no_runner_execution_proof_fields
        ),
        "no_execution_receipt_handoff": handoff,
        "no_execution_receipt_handoff_count": 1,
        "runner_invocation_boundary_closeout": boundary_closeout,
        "runner_invocation_boundary_closeout_count": 1,
        "runner_invocation_boundary": boundary,
        "runner_invocation_boundary_count": 1,
        "execution_preflight_guard_closeout": guard_closeout,
        "execution_preflight_guard_closeout_count": 1,
        "execution_preflight_guard": execution_preflight_guard,
        "execution_preflight_guard_count": 1,
        "no_write_invocation_package_closeout": package_closeout,
        "no_write_invocation_package_closeout_count": 1,
        "no_write_invocation_package": package,
        "no_write_invocation_package_count": 1,
        "invocation_receipt_closeout": invocation_closeout,
        "invocation_receipt_closeout_count": 1,
        "dry_run_invocation_readiness_receipt": receipt,
        "dry_run_invocation_readiness_receipt_count": 1,
        "apply_executor_readiness_closeout": readiness_closeout,
        "apply_executor_readiness_closeout_count": 1,
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": boundary_closeout.get("target_file"),
        "expected_sha256": boundary_closeout.get("expected_sha256"),
        "actual_sha256": boundary_closeout.get("actual_sha256"),
        "hash_matches": boundary_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "no_execution_receipt_handoff_closeout_only": True,
        "final_no_runner_execution_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_no_execution_receipt_handoff_closeout_contract = {
        "mode": "controlled_dry_run_no_execution_receipt_handoff_closeout_and_final_no_runner_execution_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout"
        ),
        "source_runner_invocation_boundary_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-runner-invocation-boundary-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_final_no_runner_execution_proof": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_no_execution_receipt_handoff_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_no_execution_receipt_handoff_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_no_execution_receipt_handoff_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_no_execution_receipt_handoff_closeout_count": 1,
            "controlled_dry_run_no_execution_receipt_handoff_closeout_field_count": len(
                handoff_closeout_fields
            ),
            "controlled_dry_run_no_execution_receipt_handoff_closeout_acceptance_gate_count": len(
                handoff_closeout_acceptance_gates
            ),
            "final_no_runner_execution_proof_count": 1,
            "final_no_runner_execution_proof_field_count": len(
                final_no_runner_execution_proof_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(boundary_closeout_result.get("success")),
        "generated_at": boundary_closeout_result.get("generated_at"),
        "source_policy": boundary_closeout_result.get("policy"),
        "stats": boundary_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_final_no_runner_execution_proof": (
            future_database_apply_controlled_dry_run_final_no_runner_execution_proof
        ),
        "controlled_dry_run_no_execution_receipt_handoff_closeout": (
            controlled_dry_run_no_execution_receipt_handoff_closeout
        ),
        "controlled_dry_run_no_execution_receipt_handoff_closeout_contract": (
            controlled_dry_run_no_execution_receipt_handoff_closeout_contract
        ),
        "controlled_dry_run_no_execution_receipt_handoff_closeout_checks": checks,
        "source_controlled_dry_run_runner_invocation_boundary_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_runner_invocation_boundary_closeout_contract": (
            boundary_contract
        ),
        "source_controlled_dry_run_runner_invocation_boundary_closeout": (
            boundary_closeout
        ),
        "source_database_apply_controlled_dry_run_no_execution_receipt_handoff": (
            future_handoff
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future final no-runner-execution proof closeout.",
            "Keep actual runner invocation disabled; this proof confirms no execution happened in this preview lane.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out final no-runner proof and bind controlled executor quarantine."""
    proof_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_proof = (
        proof_closeout_result.get(
            "future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
        )
        or {}
    )
    handoff_closeout = (
        proof_closeout_result.get(
            "controlled_dry_run_no_execution_receipt_handoff_closeout"
        )
        or {}
    )
    handoff_contract = (
        proof_closeout_result.get(
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        )
        or {}
    )
    summary = proof_closeout_result.get("summary") or {}
    safety = proof_closeout_result.get("safety") or {}
    final_proof = handoff_closeout.get("final_no_runner_execution_proof") or {}
    handoff = handoff_closeout.get("no_execution_receipt_handoff") or {}
    boundary_closeout = handoff_closeout.get("runner_invocation_boundary_closeout") or {}
    boundary = handoff_closeout.get("runner_invocation_boundary") or {}
    guard_closeout = handoff_closeout.get("execution_preflight_guard_closeout") or {}
    execution_preflight_guard = handoff_closeout.get("execution_preflight_guard") or {}
    package_closeout = handoff_closeout.get("no_write_invocation_package_closeout") or {}
    package = handoff_closeout.get("no_write_invocation_package") or {}
    invocation_closeout = handoff_closeout.get("invocation_receipt_closeout") or {}
    receipt = handoff_closeout.get("dry_run_invocation_readiness_receipt") or {}
    readiness_closeout = handoff_closeout.get("apply_executor_readiness_closeout") or {}
    readiness_contract = handoff_closeout.get("apply_executor_readiness_contract") or {}
    pre_apply_closeout = handoff_closeout.get("pre_apply_replay_closeout") or {}
    replay_verifier = handoff_closeout.get("pre_apply_replay_verifier") or {}
    final_guard = handoff_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        handoff_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = handoff_closeout.get("rollback_binding") or {}
    verifier_binding = handoff_closeout.get("post_apply_verifier_binding") or {}
    closeout_id = (
        _db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout_id(
            proof_closeout_result
        )
    )
    quarantine_id = f"{closeout_id}-controlled-executor-quarantine-proof"
    proof_closeout_fields = [
        "final_no_runner_execution_proof_closeout_id",
        "source_no_execution_receipt_handoff_closeout_id",
        "source_final_no_runner_execution_proof_id",
        "source_no_execution_receipt_handoff_id",
        "source_runner_invocation_boundary_closeout_id",
        "controlled_executor_quarantine_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    proof_closeout_acceptance_gates = [
        "no_execution_receipt_handoff_closeout_ready",
        "source_chain_ids_match",
        "final_no_runner_execution_proof_ready",
        "final_no_runner_execution_proof_no_execute",
        "controlled_executor_quarantine_proof_bound",
        "controlled_executor_quarantine_proof_blocks_execution",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    controlled_executor_quarantine_proof_fields = [
        "quarantine_proof_id",
        "source_final_no_runner_execution_proof_closeout_id",
        "source_final_no_runner_execution_proof_id",
        "source_no_execution_receipt_handoff_closeout_id",
        "source_no_execution_receipt_handoff_id",
        "source_runner_invocation_boundary_closeout_id",
        "quarantine_mode",
        "dry_run_executor_invocation_allowed",
        "runner_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_no_execution_receipt_handoff_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_final_no_runner_execution_proof_missing",
        "abort_if_final_no_runner_execution_proof_reports_execution",
        "abort_if_controlled_executor_quarantine_proof_missing",
        "abort_if_controlled_executor_quarantine_proof_allows_execution",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    controlled_executor_quarantine_proof = {
        "quarantine_proof_id": quarantine_id,
        "source_final_no_runner_execution_proof_closeout_id": closeout_id,
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "required_proof_mode": "final_no_runner_execution_proof_preview_only",
        "required_command_shape_hash": final_proof.get("required_command_shape_hash"),
        "quarantine_status": "controlled_executor_quarantine_proof_preview_ready",
        "quarantine_mode": "controlled_executor_quarantine_proof_preview_only",
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_controlled_executor_quarantine_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "controlled_executor_quarantine_proof_field_count": len(
            controlled_executor_quarantine_proof_fields
        ),
        "controlled_executor_quarantine_proof_fields": (
            controlled_executor_quarantine_proof_fields
        ),
    }
    handoff_closeout_ready = (
        proof_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_no_execution_receipt_handoff_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(handoff_closeout.get("no_execution_receipt_handoff_closeout_id"))
        and handoff_closeout.get("no_execution_receipt_handoff_closeout_id")
        == future_proof.get("no_execution_receipt_handoff_closeout_id")
        == final_proof.get("source_no_execution_receipt_handoff_closeout_id")
        == controlled_executor_quarantine_proof.get(
            "source_no_execution_receipt_handoff_closeout_id"
        )
        and final_proof.get("proof_id")
        == future_proof.get("final_no_runner_execution_proof_id")
        == controlled_executor_quarantine_proof.get(
            "source_final_no_runner_execution_proof_id"
        )
        and handoff.get("handoff_id")
        == future_proof.get("source_no_execution_receipt_handoff_id")
        == final_proof.get("source_no_execution_receipt_handoff_id")
        == controlled_executor_quarantine_proof.get(
            "source_no_execution_receipt_handoff_id"
        )
        and boundary_closeout.get("runner_invocation_boundary_closeout_id")
        == future_proof.get("source_runner_invocation_boundary_closeout_id")
        == final_proof.get("source_runner_invocation_boundary_closeout_id")
        == controlled_executor_quarantine_proof.get(
            "source_runner_invocation_boundary_closeout_id"
        )
        and boundary.get("boundary_id")
        == future_proof.get("source_runner_invocation_boundary_id")
        == controlled_executor_quarantine_proof.get(
            "source_runner_invocation_boundary_id"
        )
    )
    final_no_runner_execution_proof_ready = (
        final_proof.get("proof_status")
        == "final_no_runner_execution_proof_preview_ready"
        and final_proof.get("proof_id")
        == future_proof.get("final_no_runner_execution_proof_id")
        and int(final_proof.get("final_no_runner_execution_proof_field_count") or 0)
        == 12
        and summary.get("final_no_runner_execution_proof_count") == 1
    )
    final_no_runner_execution_proof_no_execute = (
        final_proof.get("proof_mode")
        == "final_no_runner_execution_proof_preview_only"
        and final_proof.get("execution_receipt_present") is False
        and final_proof.get("execution_receipt_required") is False
        and final_proof.get("dry_run_executor_invoked") is False
        and final_proof.get("runner_invocation_performed") is False
        and final_proof.get("endpoint_executed") is False
        and final_proof.get("sql_executed") is False
        and final_proof.get("database_written") is False
        and final_proof.get("dry_run_executor_invocation_allowed") is False
        and final_proof.get("runner_invocation_allowed") is False
        and final_proof.get("ready_for_final_no_runner_execution_proof_now")
        is False
        and final_proof.get("ready_for_dry_run_executor_invocation_now") is False
        and final_proof.get("ready_for_actual_dry_run_execution_now") is False
        and final_proof.get("endpoint_execution_allowed") is False
        and final_proof.get("sql_execution_allowed") is False
        and final_proof.get("database_write_allowed") is False
        and final_proof.get("database_apply_authorized") is False
        and final_proof.get("executes_database_apply") is False
        and final_proof.get("executes_endpoint") is False
        and final_proof.get("executes_sql") is False
        and final_proof.get("writes_database") is False
        and final_proof.get("captures_stdout") is False
        and final_proof.get("captures_stderr") is False
        and final_proof.get("stdout_included") is False
        and final_proof.get("stderr_included") is False
    )
    controlled_executor_quarantine_proof_bound = (
        bool(controlled_executor_quarantine_proof.get("quarantine_proof_id"))
        and controlled_executor_quarantine_proof.get(
            "source_final_no_runner_execution_proof_closeout_id"
        )
        == closeout_id
        and controlled_executor_quarantine_proof.get(
            "source_final_no_runner_execution_proof_id"
        )
        == final_proof.get("proof_id")
        and controlled_executor_quarantine_proof.get("required_command_shape_hash")
        == final_proof.get("required_command_shape_hash")
        and int(
            controlled_executor_quarantine_proof.get(
                "controlled_executor_quarantine_proof_field_count"
            )
            or 0
        )
        == len(controlled_executor_quarantine_proof_fields)
    )
    controlled_executor_quarantine_proof_blocks_execution = (
        controlled_executor_quarantine_proof.get("quarantine_mode")
        == "controlled_executor_quarantine_proof_preview_only"
        and controlled_executor_quarantine_proof.get(
            "controlled_executor_quarantine_bound"
        )
        is True
        and controlled_executor_quarantine_proof.get("executor_quarantine_enforced")
        is True
        and controlled_executor_quarantine_proof.get("execution_receipt_present")
        is False
        and controlled_executor_quarantine_proof.get("execution_receipt_required")
        is False
        and controlled_executor_quarantine_proof.get("dry_run_executor_invoked")
        is False
        and controlled_executor_quarantine_proof.get("runner_invocation_performed")
        is False
        and controlled_executor_quarantine_proof.get("endpoint_executed") is False
        and controlled_executor_quarantine_proof.get("sql_executed") is False
        and controlled_executor_quarantine_proof.get("database_written") is False
        and controlled_executor_quarantine_proof.get(
            "dry_run_executor_invocation_allowed"
        )
        is False
        and controlled_executor_quarantine_proof.get("runner_invocation_allowed")
        is False
        and controlled_executor_quarantine_proof.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and controlled_executor_quarantine_proof.get(
            "ready_for_actual_dry_run_execution_now"
        )
        is False
        and controlled_executor_quarantine_proof.get("endpoint_execution_allowed")
        is False
        and controlled_executor_quarantine_proof.get("sql_execution_allowed") is False
        and controlled_executor_quarantine_proof.get("database_write_allowed") is False
        and controlled_executor_quarantine_proof.get("database_apply_authorized")
        is False
        and controlled_executor_quarantine_proof.get("executes_database_apply")
        is False
        and controlled_executor_quarantine_proof.get("executes_endpoint") is False
        and controlled_executor_quarantine_proof.get("executes_sql") is False
        and controlled_executor_quarantine_proof.get("writes_database") is False
        and controlled_executor_quarantine_proof.get("captures_stdout") is False
        and controlled_executor_quarantine_proof.get("captures_stderr") is False
        and controlled_executor_quarantine_proof.get("stdout_included") is False
        and controlled_executor_quarantine_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        handoff_closeout.get("no_execution_receipt_handoff_closeout_only") is True
        and handoff_closeout.get("final_no_runner_execution_proof_only") is True
        and handoff_closeout.get("database_apply_authorized") is False
        and boundary_closeout.get("runner_invocation_boundary_closeout_only") is True
        and boundary_closeout.get("no_execution_receipt_handoff_only") is True
        and guard_closeout.get("execution_preflight_guard_closeout_only") is True
        and package_closeout.get("no_write_invocation_package_closeout_only")
        is True
        and package.get("package_mode") == "no_write_invocation_package_preview_only"
        and invocation_closeout.get("invocation_receipt_closeout_only") is True
        and receipt.get("receipt_mode") == "dry_run_invocation_readiness_preview_only"
        and readiness_contract.get("readiness_mode")
        == "apply_executor_readiness_contract_preview_only"
        and replay_verifier.get("replay_mode") == "pre_apply_replay_preview_only"
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and final_no_runner_execution_proof_no_execute
    )
    target_hash_locked = (
        handoff_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(handoff_closeout.get("expected_sha256"))
        and bool(handoff_closeout.get("actual_sha256"))
        and handoff_closeout.get("expected_sha256")
        == handoff_closeout.get("actual_sha256")
        and handoff_closeout.get("hash_matches") is True
        and handoff_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    handoff_contract_blocks_database_apply = (
        handoff_contract.get("executes_database_apply") is False
        and handoff_contract.get("executes_endpoint") is False
        and handoff_contract.get("executes_sql") is False
        and handoff_contract.get("database_apply_authorized") is False
        and handoff_contract.get("ready_for_database_apply_now") is False
        and handoff_contract.get("ready_for_dry_run_executor_invocation_now")
        is False
        and handoff_contract.get("ready_for_actual_dry_run_execution_now")
        is False
        and handoff_contract.get("signs_database_apply_authorization") is False
        and handoff_contract.get("writes_database") is False
        and handoff_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("dry_run_executor_invoked_count", 0) == 0
        and summary.get("runner_invocation_performed_count", 0) == 0
        and summary.get("endpoint_executed_count", 0) == 0
        and summary.get("sql_executed_count", 0) == 0
        and summary.get("database_written_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and final_no_runner_execution_proof_no_execute
        and controlled_executor_quarantine_proof_blocks_execution
    )
    checks = [
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "no_execution_receipt_handoff_closeout_ready",
            handoff_closeout_ready,
            {
                "result": proof_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_no_execution_receipt_handoff_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"
                ),
            },
            "wait_for_no_execution_receipt_handoff_closeout_ready",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
                    "no_execution_receipt_handoff_closeout_id"
                ),
                "final_no_runner_execution_proof_id": final_proof.get("proof_id"),
                "quarantine_proof_id": controlled_executor_quarantine_proof.get(
                    "quarantine_proof_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "final_no_runner_execution_proof_ready",
            final_no_runner_execution_proof_ready,
            {
                "proof_id": final_proof.get("proof_id"),
                "proof_status": final_proof.get("proof_status"),
                "field_count": final_proof.get(
                    "final_no_runner_execution_proof_field_count"
                ),
            },
            "wait_for_final_no_runner_execution_proof_ready",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "final_no_runner_execution_proof_no_execute",
            final_no_runner_execution_proof_no_execute,
            {
                "proof_mode": final_proof.get("proof_mode"),
                "dry_run_executor_invoked": final_proof.get(
                    "dry_run_executor_invoked"
                ),
                "runner_invocation_performed": final_proof.get(
                    "runner_invocation_performed"
                ),
            },
            "abort_if_final_no_runner_execution_proof_reports_execution",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "controlled_executor_quarantine_proof_bound",
            controlled_executor_quarantine_proof_bound,
            {
                "quarantine_proof_id": controlled_executor_quarantine_proof.get(
                    "quarantine_proof_id"
                ),
                "source_final_no_runner_execution_proof_id": (
                    controlled_executor_quarantine_proof.get(
                        "source_final_no_runner_execution_proof_id"
                    )
                ),
                "field_count": controlled_executor_quarantine_proof.get(
                    "controlled_executor_quarantine_proof_field_count"
                ),
            },
            "wait_for_controlled_executor_quarantine_proof_binding",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "controlled_executor_quarantine_proof_blocks_execution",
            controlled_executor_quarantine_proof_blocks_execution,
            {
                "quarantine_mode": controlled_executor_quarantine_proof.get(
                    "quarantine_mode"
                ),
                "dry_run_executor_invoked": controlled_executor_quarantine_proof.get(
                    "dry_run_executor_invoked"
                ),
                "runner_invocation_performed": controlled_executor_quarantine_proof.get(
                    "runner_invocation_performed"
                ),
            },
            "abort_if_controlled_executor_quarantine_proof_allows_execution",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "no_execution_receipt_handoff_closeout_only": handoff_closeout.get(
                    "no_execution_receipt_handoff_closeout_only"
                ),
                "final_no_runner_execution_proof_only": handoff_closeout.get(
                    "final_no_runner_execution_proof_only"
                ),
                "proof_mode": final_proof.get("proof_mode"),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": handoff_closeout.get("target_file"),
                "hash_matches": handoff_closeout.get("hash_matches"),
                "expected_sha256_present": bool(handoff_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(handoff_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "no_execution_receipt_handoff_closeout_contract_blocks_database_apply",
            handoff_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_final_no_runner_execution_proof": (
                    handoff_contract.get(
                        "permits_future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
                    )
                ),
                "database_apply_authorized": handoff_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": handoff_contract.get("writes_database"),
            },
            "abort_if_no_execution_receipt_handoff_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "dry_run_executor_invoked_count": summary.get(
                    "dry_run_executor_invoked_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_final_no_runner_execution_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            handoff_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": handoff_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof = {
        "final_no_runner_execution_proof_closeout_id": closeout_id,
        "controlled_executor_quarantine_proof_id": quarantine_id,
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout": (
            closeout_ready
        ),
        "final_no_runner_execution_proof_closeout_ready": closeout_ready,
        "controlled_executor_quarantine_proof_bound": closeout_ready,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_final_no_runner_execution_proof_closeout = {
        "final_no_runner_execution_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_final_no_runner_execution_proof_closeout"
        ),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "source_execution_preflight_guard_closeout_id": guard_closeout.get(
            "execution_preflight_guard_closeout_id"
        ),
        "required_command_shape_hash": final_proof.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_final_no_runner_execution_proof_closeout": (
            closeout_ready
        ),
        "final_no_runner_execution_proof_closeout_fields": proof_closeout_fields,
        "final_no_runner_execution_proof_closeout_field_count": len(
            proof_closeout_fields
        ),
        "final_no_runner_execution_proof_closeout_acceptance_gates": (
            proof_closeout_acceptance_gates
        ),
        "final_no_runner_execution_proof_closeout_acceptance_gate_count": len(
            proof_closeout_acceptance_gates
        ),
        "controlled_executor_quarantine_proof": controlled_executor_quarantine_proof,
        "controlled_executor_quarantine_proof_count": 1,
        "controlled_executor_quarantine_proof_field_count": len(
            controlled_executor_quarantine_proof_fields
        ),
        "final_no_runner_execution_proof": final_proof,
        "final_no_runner_execution_proof_count": 1,
        "no_execution_receipt_handoff_closeout": handoff_closeout,
        "no_execution_receipt_handoff_closeout_count": 1,
        "no_execution_receipt_handoff": handoff,
        "no_execution_receipt_handoff_count": 1,
        "runner_invocation_boundary_closeout": boundary_closeout,
        "runner_invocation_boundary_closeout_count": 1,
        "runner_invocation_boundary": boundary,
        "runner_invocation_boundary_count": 1,
        "execution_preflight_guard_closeout": guard_closeout,
        "execution_preflight_guard_closeout_count": 1,
        "execution_preflight_guard": execution_preflight_guard,
        "execution_preflight_guard_count": 1,
        "no_write_invocation_package_closeout": package_closeout,
        "no_write_invocation_package_closeout_count": 1,
        "no_write_invocation_package": package,
        "no_write_invocation_package_count": 1,
        "invocation_receipt_closeout": invocation_closeout,
        "invocation_receipt_closeout_count": 1,
        "dry_run_invocation_readiness_receipt": receipt,
        "dry_run_invocation_readiness_receipt_count": 1,
        "apply_executor_readiness_closeout": readiness_closeout,
        "apply_executor_readiness_closeout_count": 1,
        "apply_executor_readiness_contract": readiness_contract,
        "apply_executor_readiness_contract_count": 1,
        "pre_apply_replay_closeout": pre_apply_closeout,
        "pre_apply_replay_closeout_count": 1,
        "pre_apply_replay_verifier": replay_verifier,
        "pre_apply_replay_verifier_count": 1,
        "final_dry_run_executor_guard": final_guard,
        "final_dry_run_executor_guard_count": 1,
        "no_apply_enforcement_verification": no_apply_enforcement,
        "no_apply_enforcement_verification_count": 1,
        "target_file": handoff_closeout.get("target_file"),
        "expected_sha256": handoff_closeout.get("expected_sha256"),
        "actual_sha256": handoff_closeout.get("actual_sha256"),
        "hash_matches": handoff_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "final_no_runner_execution_proof_closeout_only": True,
        "controlled_executor_quarantine_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_final_no_runner_execution_proof_closeout_contract = {
        "mode": "controlled_dry_run_final_no_runner_execution_proof_closeout_and_controlled_executor_quarantine_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout"
        ),
        "source_no_execution_receipt_handoff_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_final_no_runner_execution_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_final_no_runner_execution_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_final_no_runner_execution_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_final_no_runner_execution_proof_closeout_count": 1,
            "controlled_dry_run_final_no_runner_execution_proof_closeout_field_count": len(
                proof_closeout_fields
            ),
            "controlled_dry_run_final_no_runner_execution_proof_closeout_acceptance_gate_count": len(
                proof_closeout_acceptance_gates
            ),
            "controlled_executor_quarantine_proof_count": 1,
            "controlled_executor_quarantine_proof_field_count": len(
                controlled_executor_quarantine_proof_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(proof_closeout_result.get("success")),
        "generated_at": proof_closeout_result.get("generated_at"),
        "source_policy": proof_closeout_result.get("policy"),
        "stats": proof_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof": (
            future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof
        ),
        "controlled_dry_run_final_no_runner_execution_proof_closeout": (
            controlled_dry_run_final_no_runner_execution_proof_closeout
        ),
        "controlled_dry_run_final_no_runner_execution_proof_closeout_contract": (
            controlled_dry_run_final_no_runner_execution_proof_closeout_contract
        ),
        "controlled_dry_run_final_no_runner_execution_proof_closeout_checks": checks,
        "source_controlled_dry_run_no_execution_receipt_handoff_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_no_execution_receipt_handoff_closeout_contract": (
            handoff_contract
        ),
        "source_controlled_dry_run_no_execution_receipt_handoff_closeout": (
            handoff_closeout
        ),
        "source_database_apply_controlled_dry_run_final_no_runner_execution_proof": (
            future_proof
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future controlled executor quarantine proof closeout.",
            "Keep actual dry-run executor invocation disabled; this proof confirms executor quarantine in this preview lane.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out executor quarantine and freeze the dry-run execution envelope."""
    quarantine_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_quarantine = (
        quarantine_closeout_result.get(
            "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
        )
        or {}
    )
    quarantine_closeout = (
        quarantine_closeout_result.get(
            "controlled_dry_run_final_no_runner_execution_proof_closeout"
        )
        or {}
    )
    quarantine_contract = (
        quarantine_closeout_result.get(
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        )
        or {}
    )
    summary = quarantine_closeout_result.get("summary") or {}
    safety = quarantine_closeout_result.get("safety") or {}
    quarantine = quarantine_closeout.get("controlled_executor_quarantine_proof") or {}
    final_proof = quarantine_closeout.get("final_no_runner_execution_proof") or {}
    handoff_closeout = (
        quarantine_closeout.get("no_execution_receipt_handoff_closeout") or {}
    )
    handoff = quarantine_closeout.get("no_execution_receipt_handoff") or {}
    boundary_closeout = (
        quarantine_closeout.get("runner_invocation_boundary_closeout") or {}
    )
    boundary = quarantine_closeout.get("runner_invocation_boundary") or {}
    guard_closeout = (
        quarantine_closeout.get("execution_preflight_guard_closeout") or {}
    )
    package_closeout = (
        quarantine_closeout.get("no_write_invocation_package_closeout") or {}
    )
    invocation_closeout = quarantine_closeout.get("invocation_receipt_closeout") or {}
    readiness_closeout = (
        quarantine_closeout.get("apply_executor_readiness_closeout") or {}
    )
    pre_apply_closeout = quarantine_closeout.get("pre_apply_replay_closeout") or {}
    final_guard = quarantine_closeout.get("final_dry_run_executor_guard") or {}
    no_apply_enforcement = (
        quarantine_closeout.get("no_apply_enforcement_verification") or {}
    )
    rollback_binding = quarantine_closeout.get("rollback_binding") or {}
    verifier_binding = quarantine_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = quarantine_closeout.get(
        "final_no_runner_execution_proof_closeout_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout_id(
            quarantine_closeout_result
        )
    )
    freeze_id = f"{closeout_id}-dry-run-execution-envelope-freeze-proof"
    quarantine_closeout_fields = [
        "controlled_executor_quarantine_proof_closeout_id",
        "source_final_no_runner_execution_proof_closeout_id",
        "source_controlled_executor_quarantine_proof_id",
        "source_final_no_runner_execution_proof_id",
        "dry_run_execution_envelope_freeze_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "execution_envelope_frozen",
        "dry_run_executor_invocation_allowed",
        "abort_conditions",
    ]
    quarantine_closeout_acceptance_gates = [
        "final_no_runner_execution_proof_closeout_ready",
        "source_chain_ids_match",
        "controlled_executor_quarantine_proof_ready",
        "controlled_executor_quarantine_proof_no_execute",
        "dry_run_execution_envelope_freeze_proof_bound",
        "dry_run_execution_envelope_freeze_proof_blocks_execution",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    dry_run_execution_envelope_freeze_proof_fields = [
        "freeze_proof_id",
        "source_controlled_executor_quarantine_proof_closeout_id",
        "source_controlled_executor_quarantine_proof_id",
        "source_final_no_runner_execution_proof_closeout_id",
        "source_final_no_runner_execution_proof_id",
        "source_no_execution_receipt_handoff_closeout_id",
        "freeze_mode",
        "execution_envelope_frozen",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_final_no_runner_execution_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_controlled_executor_quarantine_proof_missing",
        "abort_if_controlled_executor_quarantine_proof_reports_execution",
        "abort_if_dry_run_execution_envelope_freeze_proof_missing",
        "abort_if_execution_envelope_is_mutable_or_allows_execution",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    dry_run_execution_envelope_freeze_proof = {
        "freeze_proof_id": freeze_id,
        "source_controlled_executor_quarantine_proof_closeout_id": closeout_id,
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": source_closeout_id,
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "required_command_shape_hash": quarantine.get("required_command_shape_hash"),
        "freeze_status": "dry_run_execution_envelope_freeze_proof_preview_ready",
        "freeze_mode": "dry_run_execution_envelope_freeze_proof_preview_only",
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_controlled_executor_quarantine_closeout_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "dry_run_execution_envelope_freeze_proof_field_count": len(
            dry_run_execution_envelope_freeze_proof_fields
        ),
        "dry_run_execution_envelope_freeze_proof_fields": (
            dry_run_execution_envelope_freeze_proof_fields
        ),
    }
    quarantine_closeout_ready = (
        quarantine_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_final_no_runner_execution_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_final_no_runner_execution_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_quarantine.get("final_no_runner_execution_proof_closeout_id")
        == quarantine.get("source_final_no_runner_execution_proof_closeout_id")
        == dry_run_execution_envelope_freeze_proof.get(
            "source_final_no_runner_execution_proof_closeout_id"
        )
        and quarantine.get("quarantine_proof_id")
        == future_quarantine.get("controlled_executor_quarantine_proof_id")
        == dry_run_execution_envelope_freeze_proof.get(
            "source_controlled_executor_quarantine_proof_id"
        )
        and final_proof.get("proof_id")
        == future_quarantine.get("source_final_no_runner_execution_proof_id")
        == quarantine.get("source_final_no_runner_execution_proof_id")
        == dry_run_execution_envelope_freeze_proof.get(
            "source_final_no_runner_execution_proof_id"
        )
        and handoff_closeout.get("no_execution_receipt_handoff_closeout_id")
        == future_quarantine.get("source_no_execution_receipt_handoff_closeout_id")
        == quarantine.get("source_no_execution_receipt_handoff_closeout_id")
        == dry_run_execution_envelope_freeze_proof.get(
            "source_no_execution_receipt_handoff_closeout_id"
        )
        and handoff.get("handoff_id")
        == future_quarantine.get("source_no_execution_receipt_handoff_id")
        == quarantine.get("source_no_execution_receipt_handoff_id")
        == dry_run_execution_envelope_freeze_proof.get(
            "source_no_execution_receipt_handoff_id"
        )
        and boundary_closeout.get("runner_invocation_boundary_closeout_id")
        == future_quarantine.get("source_runner_invocation_boundary_closeout_id")
        == quarantine.get("source_runner_invocation_boundary_closeout_id")
        == dry_run_execution_envelope_freeze_proof.get(
            "source_runner_invocation_boundary_closeout_id"
        )
    )
    controlled_executor_quarantine_proof_ready = (
        quarantine_closeout_ready
        and quarantine.get("quarantine_status")
        == "controlled_executor_quarantine_proof_preview_ready"
        and quarantine.get("quarantine_proof_id")
        == future_quarantine.get("controlled_executor_quarantine_proof_id")
        and int(quarantine.get("controlled_executor_quarantine_proof_field_count") or 0)
        == 12
        and summary.get("controlled_executor_quarantine_proof_count") == 1
    )
    controlled_executor_quarantine_proof_no_execute = (
        quarantine.get("quarantine_mode")
        == "controlled_executor_quarantine_proof_preview_only"
        and quarantine.get("controlled_executor_quarantine_bound") is True
        and quarantine.get("executor_quarantine_enforced") is True
        and quarantine.get("execution_receipt_present") is False
        and quarantine.get("execution_receipt_required") is False
        and quarantine.get("dry_run_executor_invoked") is False
        and quarantine.get("runner_invocation_performed") is False
        and quarantine.get("endpoint_executed") is False
        and quarantine.get("sql_executed") is False
        and quarantine.get("database_written") is False
        and quarantine.get("dry_run_executor_invocation_allowed") is False
        and quarantine.get("runner_invocation_allowed") is False
        and quarantine.get("ready_for_dry_run_executor_invocation_now") is False
        and quarantine.get("ready_for_actual_dry_run_execution_now") is False
        and quarantine.get("endpoint_execution_allowed") is False
        and quarantine.get("sql_execution_allowed") is False
        and quarantine.get("database_write_allowed") is False
        and quarantine.get("database_apply_authorized") is False
        and quarantine.get("executes_database_apply") is False
        and quarantine.get("executes_endpoint") is False
        and quarantine.get("executes_sql") is False
        and quarantine.get("writes_database") is False
        and quarantine.get("captures_stdout") is False
        and quarantine.get("captures_stderr") is False
        and quarantine.get("stdout_included") is False
        and quarantine.get("stderr_included") is False
    )
    dry_run_execution_envelope_freeze_proof_bound = (
        controlled_executor_quarantine_proof_ready
        and bool(dry_run_execution_envelope_freeze_proof.get("freeze_proof_id"))
        and dry_run_execution_envelope_freeze_proof.get(
            "source_controlled_executor_quarantine_proof_closeout_id"
        )
        == closeout_id
        and dry_run_execution_envelope_freeze_proof.get(
            "source_controlled_executor_quarantine_proof_id"
        )
        == quarantine.get("quarantine_proof_id")
        and dry_run_execution_envelope_freeze_proof.get("required_command_shape_hash")
        == quarantine.get("required_command_shape_hash")
        and int(
            dry_run_execution_envelope_freeze_proof.get(
                "dry_run_execution_envelope_freeze_proof_field_count"
            )
            or 0
        )
        == len(dry_run_execution_envelope_freeze_proof_fields)
    )
    dry_run_execution_envelope_freeze_proof_blocks_execution = (
        dry_run_execution_envelope_freeze_proof.get("freeze_mode")
        == "dry_run_execution_envelope_freeze_proof_preview_only"
        and dry_run_execution_envelope_freeze_proof.get("execution_envelope_frozen")
        is True
        and dry_run_execution_envelope_freeze_proof.get(
            "execution_envelope_mutation_allowed"
        )
        is False
        and dry_run_execution_envelope_freeze_proof.get("dry_run_executor_invoked")
        is False
        and dry_run_execution_envelope_freeze_proof.get("runner_invocation_performed")
        is False
        and dry_run_execution_envelope_freeze_proof.get("endpoint_executed") is False
        and dry_run_execution_envelope_freeze_proof.get("sql_executed") is False
        and dry_run_execution_envelope_freeze_proof.get("database_written") is False
        and dry_run_execution_envelope_freeze_proof.get("execution_receipt_present")
        is False
        and dry_run_execution_envelope_freeze_proof.get("execution_receipt_required")
        is False
        and dry_run_execution_envelope_freeze_proof.get(
            "dry_run_executor_invocation_allowed"
        )
        is False
        and dry_run_execution_envelope_freeze_proof.get("runner_invocation_allowed")
        is False
        and dry_run_execution_envelope_freeze_proof.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and dry_run_execution_envelope_freeze_proof.get(
            "ready_for_actual_dry_run_execution_now"
        )
        is False
        and dry_run_execution_envelope_freeze_proof.get("endpoint_execution_allowed")
        is False
        and dry_run_execution_envelope_freeze_proof.get("sql_execution_allowed")
        is False
        and dry_run_execution_envelope_freeze_proof.get("database_write_allowed")
        is False
        and dry_run_execution_envelope_freeze_proof.get("database_apply_authorized")
        is False
        and dry_run_execution_envelope_freeze_proof.get("executes_database_apply")
        is False
        and dry_run_execution_envelope_freeze_proof.get("executes_endpoint") is False
        and dry_run_execution_envelope_freeze_proof.get("executes_sql") is False
        and dry_run_execution_envelope_freeze_proof.get("writes_database") is False
        and dry_run_execution_envelope_freeze_proof.get("captures_stdout") is False
        and dry_run_execution_envelope_freeze_proof.get("captures_stderr") is False
        and dry_run_execution_envelope_freeze_proof.get("stdout_included") is False
        and dry_run_execution_envelope_freeze_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        quarantine_closeout.get("final_no_runner_execution_proof_closeout_only")
        is True
        and quarantine_closeout.get("controlled_executor_quarantine_proof_only")
        is True
        and quarantine_closeout.get("database_apply_authorized") is False
        and handoff_closeout.get("no_execution_receipt_handoff_closeout_only") is True
        and boundary_closeout.get("runner_invocation_boundary_closeout_only") is True
        and guard_closeout.get("execution_preflight_guard_closeout_only") is True
        and package_closeout.get("no_write_invocation_package_closeout_only")
        is True
        and invocation_closeout.get("invocation_receipt_closeout_only") is True
        and readiness_closeout.get("apply_executor_readiness_closeout_only") is True
        and pre_apply_closeout.get("pre_apply_replay_closeout_only") is True
        and final_guard.get("guard_status")
        == "final_dry_run_executor_guard_preview_ready"
        and no_apply_enforcement.get("enforcement_status")
        == "no_apply_enforcement_preview_ready"
        and controlled_executor_quarantine_proof_no_execute
    )
    target_hash_locked = (
        quarantine_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(quarantine_closeout.get("expected_sha256"))
        and bool(quarantine_closeout.get("actual_sha256"))
        and quarantine_closeout.get("expected_sha256")
        == quarantine_closeout.get("actual_sha256")
        and quarantine_closeout.get("hash_matches") is True
        and quarantine_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    quarantine_contract_blocks_database_apply = (
        quarantine_contract.get("executes_database_apply") is False
        and quarantine_contract.get("executes_endpoint") is False
        and quarantine_contract.get("executes_sql") is False
        and quarantine_contract.get("database_apply_authorized") is False
        and quarantine_contract.get("ready_for_database_apply_now") is False
        and quarantine_contract.get("ready_for_dry_run_executor_invocation_now")
        is False
        and quarantine_contract.get("ready_for_actual_dry_run_execution_now")
        is False
        and quarantine_contract.get("signs_database_apply_authorization") is False
        and quarantine_contract.get("writes_database") is False
        and quarantine_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("dry_run_executor_invoked_count", 0) == 0
        and summary.get("runner_invocation_performed_count", 0) == 0
        and summary.get("endpoint_executed_count", 0) == 0
        and summary.get("sql_executed_count", 0) == 0
        and summary.get("database_written_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and controlled_executor_quarantine_proof_no_execute
        and dry_run_execution_envelope_freeze_proof_blocks_execution
    )
    checks = [
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "final_no_runner_execution_proof_closeout_ready",
            quarantine_closeout_ready,
            {
                "result": quarantine_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_final_no_runner_execution_proof_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_final_no_runner_execution_proof_closeout_check_count"
                ),
            },
            "wait_for_final_no_runner_execution_proof_closeout_ready",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "final_no_runner_execution_proof_closeout_id": source_closeout_id,
                "controlled_executor_quarantine_proof_id": quarantine.get(
                    "quarantine_proof_id"
                ),
                "freeze_proof_id": dry_run_execution_envelope_freeze_proof.get(
                    "freeze_proof_id"
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "controlled_executor_quarantine_proof_ready",
            controlled_executor_quarantine_proof_ready,
            {
                "quarantine_proof_id": quarantine.get("quarantine_proof_id"),
                "quarantine_status": quarantine.get("quarantine_status"),
                "field_count": quarantine.get(
                    "controlled_executor_quarantine_proof_field_count"
                ),
            },
            "wait_for_controlled_executor_quarantine_proof_ready",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "controlled_executor_quarantine_proof_no_execute",
            controlled_executor_quarantine_proof_no_execute,
            {
                "quarantine_mode": quarantine.get("quarantine_mode"),
                "dry_run_executor_invoked": quarantine.get("dry_run_executor_invoked"),
                "runner_invocation_performed": quarantine.get(
                    "runner_invocation_performed"
                ),
            },
            "abort_if_controlled_executor_quarantine_proof_reports_execution",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "dry_run_execution_envelope_freeze_proof_bound",
            dry_run_execution_envelope_freeze_proof_bound,
            {
                "freeze_proof_id": dry_run_execution_envelope_freeze_proof.get(
                    "freeze_proof_id"
                ),
                "source_controlled_executor_quarantine_proof_id": (
                    dry_run_execution_envelope_freeze_proof.get(
                        "source_controlled_executor_quarantine_proof_id"
                    )
                ),
                "field_count": dry_run_execution_envelope_freeze_proof.get(
                    "dry_run_execution_envelope_freeze_proof_field_count"
                ),
            },
            "wait_for_dry_run_execution_envelope_freeze_proof_binding",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "dry_run_execution_envelope_freeze_proof_blocks_execution",
            dry_run_execution_envelope_freeze_proof_blocks_execution,
            {
                "freeze_mode": dry_run_execution_envelope_freeze_proof.get(
                    "freeze_mode"
                ),
                "execution_envelope_frozen": (
                    dry_run_execution_envelope_freeze_proof.get(
                        "execution_envelope_frozen"
                    )
                ),
                "execution_envelope_mutation_allowed": (
                    dry_run_execution_envelope_freeze_proof.get(
                        "execution_envelope_mutation_allowed"
                    )
                ),
            },
            "abort_if_execution_envelope_allows_execution",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "final_no_runner_execution_proof_closeout_only": (
                    quarantine_closeout.get(
                        "final_no_runner_execution_proof_closeout_only"
                    )
                ),
                "controlled_executor_quarantine_proof_only": (
                    quarantine_closeout.get("controlled_executor_quarantine_proof_only")
                ),
                "quarantine_mode": quarantine.get("quarantine_mode"),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": quarantine_closeout.get("target_file"),
                "hash_matches": quarantine_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    quarantine_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(
                    quarantine_closeout.get("actual_sha256")
                ),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "final_no_runner_execution_proof_closeout_contract_blocks_database_apply",
            quarantine_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof": (
                    quarantine_contract.get(
                        "permits_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
                    )
                ),
                "database_apply_authorized": quarantine_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": quarantine_contract.get("writes_database"),
            },
            "abort_if_final_no_runner_execution_proof_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "dry_run_executor_invoked_count": summary.get(
                    "dry_run_executor_invoked_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_controlled_executor_quarantine_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            quarantine_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": quarantine_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_execution_envelope_freeze_proof = {
        "controlled_executor_quarantine_proof_closeout_id": closeout_id,
        "dry_run_execution_envelope_freeze_proof_id": freeze_id,
        "source_final_no_runner_execution_proof_closeout_id": source_closeout_id,
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout": (
            closeout_ready
        ),
        "controlled_executor_quarantine_proof_closeout_ready": closeout_ready,
        "dry_run_execution_envelope_freeze_proof_bound": closeout_ready,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_controlled_executor_quarantine_proof_closeout = {
        "controlled_executor_quarantine_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
        ),
        "source_final_no_runner_execution_proof_closeout_id": source_closeout_id,
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "source_runner_invocation_boundary_id": boundary.get("boundary_id"),
        "required_command_shape_hash": quarantine.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout": (
            closeout_ready
        ),
        "controlled_executor_quarantine_proof_closeout_fields": (
            quarantine_closeout_fields
        ),
        "controlled_executor_quarantine_proof_closeout_field_count": len(
            quarantine_closeout_fields
        ),
        "controlled_executor_quarantine_proof_closeout_acceptance_gates": (
            quarantine_closeout_acceptance_gates
        ),
        "controlled_executor_quarantine_proof_closeout_acceptance_gate_count": len(
            quarantine_closeout_acceptance_gates
        ),
        "dry_run_execution_envelope_freeze_proof": (
            dry_run_execution_envelope_freeze_proof
        ),
        "dry_run_execution_envelope_freeze_proof_count": 1,
        "dry_run_execution_envelope_freeze_proof_field_count": len(
            dry_run_execution_envelope_freeze_proof_fields
        ),
        "controlled_executor_quarantine_proof": quarantine,
        "controlled_executor_quarantine_proof_count": 1,
        "final_no_runner_execution_proof_closeout": quarantine_closeout,
        "final_no_runner_execution_proof_closeout_count": 1,
        "final_no_runner_execution_proof": final_proof,
        "final_no_runner_execution_proof_count": 1,
        "no_execution_receipt_handoff_closeout": handoff_closeout,
        "no_execution_receipt_handoff_closeout_count": 1,
        "no_execution_receipt_handoff": handoff,
        "no_execution_receipt_handoff_count": 1,
        "runner_invocation_boundary_closeout": boundary_closeout,
        "runner_invocation_boundary_closeout_count": 1,
        "runner_invocation_boundary": boundary,
        "runner_invocation_boundary_count": 1,
        "target_file": quarantine_closeout.get("target_file"),
        "expected_sha256": quarantine_closeout.get("expected_sha256"),
        "actual_sha256": quarantine_closeout.get("actual_sha256"),
        "hash_matches": quarantine_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "controlled_executor_quarantine_proof_closeout_only": True,
        "dry_run_execution_envelope_freeze_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract = {
        "mode": "controlled_dry_run_controlled_executor_quarantine_proof_closeout_and_execution_envelope_freeze_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-controlled-executor-quarantine-proof-closeout"
        ),
        "source_final_no_runner_execution_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_count": 1,
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_field_count": len(
                quarantine_closeout_fields
            ),
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_acceptance_gate_count": len(
                quarantine_closeout_acceptance_gates
            ),
            "dry_run_execution_envelope_freeze_proof_count": 1,
            "dry_run_execution_envelope_freeze_proof_field_count": len(
                dry_run_execution_envelope_freeze_proof_fields
            ),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(quarantine_closeout_result.get("success")),
        "generated_at": quarantine_closeout_result.get("generated_at"),
        "source_policy": quarantine_closeout_result.get("policy"),
        "stats": quarantine_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof": (
            future_database_apply_controlled_dry_run_execution_envelope_freeze_proof
        ),
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout": (
            controlled_dry_run_controlled_executor_quarantine_proof_closeout
        ),
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract": (
            controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract
        ),
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_final_no_runner_execution_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_final_no_runner_execution_proof_closeout_contract": (
            quarantine_contract
        ),
        "source_controlled_dry_run_final_no_runner_execution_proof_closeout": (
            quarantine_closeout
        ),
        "source_database_apply_controlled_dry_run_controlled_executor_quarantine_proof": (
            future_quarantine
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future execution envelope freeze proof closeout.",
            "Keep actual dry-run executor invocation disabled; this proof freezes the preview envelope before any executor lane can run.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the frozen execution envelope and hand it to verifier preview."""
    freeze_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_freeze = (
        freeze_closeout_result.get(
            "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
        )
        or {}
    )
    freeze_closeout = (
        freeze_closeout_result.get(
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
        )
        or {}
    )
    freeze_contract = (
        freeze_closeout_result.get(
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        )
        or {}
    )
    summary = freeze_closeout_result.get("summary") or {}
    safety = freeze_closeout_result.get("safety") or {}
    freeze_proof = freeze_closeout.get("dry_run_execution_envelope_freeze_proof") or {}
    quarantine = freeze_closeout.get("controlled_executor_quarantine_proof") or {}
    source_quarantine_closeout = (
        freeze_closeout.get("final_no_runner_execution_proof_closeout") or {}
    )
    final_proof = freeze_closeout.get("final_no_runner_execution_proof") or {}
    handoff_closeout = (
        freeze_closeout.get("no_execution_receipt_handoff_closeout") or {}
    )
    handoff = freeze_closeout.get("no_execution_receipt_handoff") or {}
    boundary_closeout = (
        freeze_closeout.get("runner_invocation_boundary_closeout") or {}
    )
    rollback_binding = freeze_closeout.get("rollback_binding") or {}
    verifier_binding = freeze_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = freeze_closeout.get(
        "controlled_executor_quarantine_proof_closeout_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout_id(
            freeze_closeout_result
        )
    )
    handoff_id = f"{closeout_id}-frozen-envelope-verifier-handoff"
    freeze_closeout_fields = [
        "execution_envelope_freeze_proof_closeout_id",
        "source_controlled_executor_quarantine_proof_closeout_id",
        "source_dry_run_execution_envelope_freeze_proof_id",
        "source_controlled_executor_quarantine_proof_id",
        "frozen_envelope_verifier_handoff_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "execution_envelope_frozen",
        "verifier_invocation_allowed",
        "abort_conditions",
    ]
    freeze_closeout_acceptance_gates = [
        "controlled_executor_quarantine_proof_closeout_ready",
        "source_chain_ids_match",
        "dry_run_execution_envelope_freeze_proof_ready",
        "dry_run_execution_envelope_freeze_proof_no_execute",
        "frozen_envelope_verifier_handoff_bound",
        "frozen_envelope_verifier_handoff_blocks_execution",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    frozen_envelope_verifier_handoff_fields = [
        "handoff_id",
        "source_execution_envelope_freeze_proof_closeout_id",
        "source_dry_run_execution_envelope_freeze_proof_id",
        "source_controlled_executor_quarantine_proof_closeout_id",
        "source_controlled_executor_quarantine_proof_id",
        "verifier_handoff_mode",
        "execution_envelope_frozen",
        "verifier_invocation_allowed",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_controlled_executor_quarantine_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_dry_run_execution_envelope_freeze_proof_missing",
        "abort_if_dry_run_execution_envelope_freeze_proof_reports_execution",
        "abort_if_frozen_envelope_verifier_handoff_missing",
        "abort_if_verifier_handoff_allows_execution",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    frozen_envelope_verifier_handoff = {
        "handoff_id": handoff_id,
        "source_execution_envelope_freeze_proof_closeout_id": closeout_id,
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_closeout_id": source_closeout_id,
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": (
            source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_id")
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "required_command_shape_hash": freeze_proof.get("required_command_shape_hash"),
        "handoff_status": "frozen_envelope_verifier_handoff_preview_ready",
        "verifier_handoff_mode": "frozen_envelope_verifier_handoff_preview_only",
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_handoff_bound": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_frozen_envelope_verifier_handoff_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "frozen_envelope_verifier_handoff_field_count": len(
            frozen_envelope_verifier_handoff_fields
        ),
        "frozen_envelope_verifier_handoff_fields": (
            frozen_envelope_verifier_handoff_fields
        ),
    }
    freeze_closeout_ready = (
        freeze_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_freeze.get("controlled_executor_quarantine_proof_closeout_id")
        == freeze_proof.get("source_controlled_executor_quarantine_proof_closeout_id")
        == frozen_envelope_verifier_handoff.get(
            "source_controlled_executor_quarantine_proof_closeout_id"
        )
        and freeze_proof.get("freeze_proof_id")
        == future_freeze.get("dry_run_execution_envelope_freeze_proof_id")
        == frozen_envelope_verifier_handoff.get(
            "source_dry_run_execution_envelope_freeze_proof_id"
        )
        and quarantine.get("quarantine_proof_id")
        == future_freeze.get("source_controlled_executor_quarantine_proof_id")
        == freeze_proof.get("source_controlled_executor_quarantine_proof_id")
        == frozen_envelope_verifier_handoff.get(
            "source_controlled_executor_quarantine_proof_id"
        )
        and final_proof.get("proof_id")
        == future_freeze.get("source_final_no_runner_execution_proof_id")
        == freeze_proof.get("source_final_no_runner_execution_proof_id")
        == frozen_envelope_verifier_handoff.get(
            "source_final_no_runner_execution_proof_id"
        )
        and handoff_closeout.get("no_execution_receipt_handoff_closeout_id")
        == future_freeze.get("source_no_execution_receipt_handoff_closeout_id")
        == freeze_proof.get("source_no_execution_receipt_handoff_closeout_id")
        == frozen_envelope_verifier_handoff.get(
            "source_no_execution_receipt_handoff_closeout_id"
        )
    )
    dry_run_execution_envelope_freeze_proof_ready = (
        freeze_closeout_ready
        and freeze_proof.get("freeze_status")
        == "dry_run_execution_envelope_freeze_proof_preview_ready"
        and freeze_proof.get("freeze_proof_id")
        == future_freeze.get("dry_run_execution_envelope_freeze_proof_id")
        and int(freeze_proof.get("dry_run_execution_envelope_freeze_proof_field_count") or 0)
        == 12
        and summary.get("dry_run_execution_envelope_freeze_proof_count") == 1
    )
    dry_run_execution_envelope_freeze_proof_no_execute = (
        freeze_proof.get("freeze_mode")
        == "dry_run_execution_envelope_freeze_proof_preview_only"
        and freeze_proof.get("execution_envelope_frozen") is True
        and freeze_proof.get("execution_envelope_mutation_allowed") is False
        and freeze_proof.get("dry_run_executor_invoked") is False
        and freeze_proof.get("runner_invocation_performed") is False
        and freeze_proof.get("endpoint_executed") is False
        and freeze_proof.get("sql_executed") is False
        and freeze_proof.get("database_written") is False
        and freeze_proof.get("execution_receipt_present") is False
        and freeze_proof.get("execution_receipt_required") is False
        and freeze_proof.get("dry_run_executor_invocation_allowed") is False
        and freeze_proof.get("runner_invocation_allowed") is False
        and freeze_proof.get("ready_for_dry_run_executor_invocation_now") is False
        and freeze_proof.get("ready_for_actual_dry_run_execution_now") is False
        and freeze_proof.get("endpoint_execution_allowed") is False
        and freeze_proof.get("sql_execution_allowed") is False
        and freeze_proof.get("database_write_allowed") is False
        and freeze_proof.get("database_apply_authorized") is False
        and freeze_proof.get("executes_database_apply") is False
        and freeze_proof.get("executes_endpoint") is False
        and freeze_proof.get("executes_sql") is False
        and freeze_proof.get("writes_database") is False
        and freeze_proof.get("captures_stdout") is False
        and freeze_proof.get("captures_stderr") is False
        and freeze_proof.get("stdout_included") is False
        and freeze_proof.get("stderr_included") is False
    )
    frozen_envelope_verifier_handoff_bound = (
        dry_run_execution_envelope_freeze_proof_ready
        and bool(frozen_envelope_verifier_handoff.get("handoff_id"))
        and frozen_envelope_verifier_handoff.get(
            "source_execution_envelope_freeze_proof_closeout_id"
        )
        == closeout_id
        and frozen_envelope_verifier_handoff.get(
            "source_dry_run_execution_envelope_freeze_proof_id"
        )
        == freeze_proof.get("freeze_proof_id")
        and frozen_envelope_verifier_handoff.get("required_command_shape_hash")
        == freeze_proof.get("required_command_shape_hash")
        and int(
            frozen_envelope_verifier_handoff.get(
                "frozen_envelope_verifier_handoff_field_count"
            )
            or 0
        )
        == len(frozen_envelope_verifier_handoff_fields)
    )
    frozen_envelope_verifier_handoff_blocks_execution = (
        frozen_envelope_verifier_handoff.get("verifier_handoff_mode")
        == "frozen_envelope_verifier_handoff_preview_only"
        and frozen_envelope_verifier_handoff.get("execution_envelope_frozen") is True
        and frozen_envelope_verifier_handoff.get(
            "execution_envelope_mutation_allowed"
        )
        is False
        and frozen_envelope_verifier_handoff.get("verifier_handoff_bound") is True
        and frozen_envelope_verifier_handoff.get("verifier_invocation_allowed")
        is False
        and frozen_envelope_verifier_handoff.get("verifier_invoked") is False
        and frozen_envelope_verifier_handoff.get("verifier_receipt_present") is False
        and frozen_envelope_verifier_handoff.get("verifier_receipt_required") is False
        and frozen_envelope_verifier_handoff.get("dry_run_executor_invoked") is False
        and frozen_envelope_verifier_handoff.get("runner_invocation_performed")
        is False
        and frozen_envelope_verifier_handoff.get("endpoint_executed") is False
        and frozen_envelope_verifier_handoff.get("sql_executed") is False
        and frozen_envelope_verifier_handoff.get("database_written") is False
        and frozen_envelope_verifier_handoff.get("execution_receipt_present") is False
        and frozen_envelope_verifier_handoff.get("execution_receipt_required") is False
        and frozen_envelope_verifier_handoff.get("dry_run_executor_invocation_allowed")
        is False
        and frozen_envelope_verifier_handoff.get("runner_invocation_allowed") is False
        and frozen_envelope_verifier_handoff.get("ready_for_verifier_invocation_now")
        is False
        and frozen_envelope_verifier_handoff.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and frozen_envelope_verifier_handoff.get("ready_for_actual_dry_run_execution_now")
        is False
        and frozen_envelope_verifier_handoff.get("endpoint_execution_allowed") is False
        and frozen_envelope_verifier_handoff.get("sql_execution_allowed") is False
        and frozen_envelope_verifier_handoff.get("database_write_allowed") is False
        and frozen_envelope_verifier_handoff.get("database_apply_authorized") is False
        and frozen_envelope_verifier_handoff.get("executes_database_apply") is False
        and frozen_envelope_verifier_handoff.get("executes_endpoint") is False
        and frozen_envelope_verifier_handoff.get("executes_sql") is False
        and frozen_envelope_verifier_handoff.get("writes_database") is False
        and frozen_envelope_verifier_handoff.get("captures_stdout") is False
        and frozen_envelope_verifier_handoff.get("captures_stderr") is False
        and frozen_envelope_verifier_handoff.get("stdout_included") is False
        and frozen_envelope_verifier_handoff.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        freeze_closeout.get("controlled_executor_quarantine_proof_closeout_only")
        is True
        and freeze_closeout.get("dry_run_execution_envelope_freeze_proof_only")
        is True
        and freeze_closeout.get("database_apply_authorized") is False
        and source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_only")
        is True
        and source_quarantine_closeout.get("controlled_executor_quarantine_proof_only")
        is True
        and handoff_closeout.get("no_execution_receipt_handoff_closeout_only") is True
        and boundary_closeout.get("runner_invocation_boundary_closeout_only") is True
        and dry_run_execution_envelope_freeze_proof_no_execute
    )
    target_hash_locked = (
        freeze_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(freeze_closeout.get("expected_sha256"))
        and bool(freeze_closeout.get("actual_sha256"))
        and freeze_closeout.get("expected_sha256")
        == freeze_closeout.get("actual_sha256")
        and freeze_closeout.get("hash_matches") is True
        and freeze_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    freeze_contract_blocks_database_apply = (
        freeze_contract.get("executes_database_apply") is False
        and freeze_contract.get("executes_endpoint") is False
        and freeze_contract.get("executes_sql") is False
        and freeze_contract.get("database_apply_authorized") is False
        and freeze_contract.get("ready_for_database_apply_now") is False
        and freeze_contract.get("ready_for_dry_run_executor_invocation_now") is False
        and freeze_contract.get("ready_for_actual_dry_run_execution_now") is False
        and freeze_contract.get("signs_database_apply_authorization") is False
        and freeze_contract.get("writes_database") is False
        and freeze_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("dry_run_executor_invoked_count", 0) == 0
        and summary.get("runner_invocation_performed_count", 0) == 0
        and summary.get("endpoint_executed_count", 0) == 0
        and summary.get("sql_executed_count", 0) == 0
        and summary.get("database_written_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and dry_run_execution_envelope_freeze_proof_no_execute
        and frozen_envelope_verifier_handoff_blocks_execution
    )
    checks = [
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "controlled_executor_quarantine_proof_closeout_ready",
            freeze_closeout_ready,
            {
                "result": freeze_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_controlled_executor_quarantine_proof_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count"
                ),
            },
            "wait_for_controlled_executor_quarantine_proof_closeout_ready",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "controlled_executor_quarantine_proof_closeout_id": source_closeout_id,
                "freeze_proof_id": freeze_proof.get("freeze_proof_id"),
                "handoff_id": frozen_envelope_verifier_handoff.get("handoff_id"),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "dry_run_execution_envelope_freeze_proof_ready",
            dry_run_execution_envelope_freeze_proof_ready,
            {
                "freeze_proof_id": freeze_proof.get("freeze_proof_id"),
                "freeze_status": freeze_proof.get("freeze_status"),
                "field_count": freeze_proof.get(
                    "dry_run_execution_envelope_freeze_proof_field_count"
                ),
            },
            "wait_for_dry_run_execution_envelope_freeze_proof_ready",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "dry_run_execution_envelope_freeze_proof_no_execute",
            dry_run_execution_envelope_freeze_proof_no_execute,
            {
                "freeze_mode": freeze_proof.get("freeze_mode"),
                "execution_envelope_frozen": freeze_proof.get(
                    "execution_envelope_frozen"
                ),
                "execution_envelope_mutation_allowed": freeze_proof.get(
                    "execution_envelope_mutation_allowed"
                ),
            },
            "abort_if_dry_run_execution_envelope_freeze_proof_reports_execution",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "frozen_envelope_verifier_handoff_bound",
            frozen_envelope_verifier_handoff_bound,
            {
                "handoff_id": frozen_envelope_verifier_handoff.get("handoff_id"),
                "source_dry_run_execution_envelope_freeze_proof_id": (
                    frozen_envelope_verifier_handoff.get(
                        "source_dry_run_execution_envelope_freeze_proof_id"
                    )
                ),
                "field_count": frozen_envelope_verifier_handoff.get(
                    "frozen_envelope_verifier_handoff_field_count"
                ),
            },
            "wait_for_frozen_envelope_verifier_handoff_binding",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "frozen_envelope_verifier_handoff_blocks_execution",
            frozen_envelope_verifier_handoff_blocks_execution,
            {
                "verifier_handoff_mode": frozen_envelope_verifier_handoff.get(
                    "verifier_handoff_mode"
                ),
                "verifier_invocation_allowed": frozen_envelope_verifier_handoff.get(
                    "verifier_invocation_allowed"
                ),
                "verifier_invoked": frozen_envelope_verifier_handoff.get(
                    "verifier_invoked"
                ),
            },
            "abort_if_frozen_envelope_verifier_handoff_allows_execution",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "controlled_executor_quarantine_proof_closeout_only": (
                    freeze_closeout.get(
                        "controlled_executor_quarantine_proof_closeout_only"
                    )
                ),
                "dry_run_execution_envelope_freeze_proof_only": (
                    freeze_closeout.get("dry_run_execution_envelope_freeze_proof_only")
                ),
                "freeze_mode": freeze_proof.get("freeze_mode"),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": freeze_closeout.get("target_file"),
                "hash_matches": freeze_closeout.get("hash_matches"),
                "expected_sha256_present": bool(freeze_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(freeze_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "controlled_executor_quarantine_proof_closeout_contract_blocks_database_apply",
            freeze_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof": (
                    freeze_contract.get(
                        "permits_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
                    )
                ),
                "database_apply_authorized": freeze_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": freeze_contract.get("writes_database"),
            },
            "abort_if_controlled_executor_quarantine_proof_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
                "dry_run_executor_invoked_count": summary.get(
                    "dry_run_executor_invoked_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_execution_envelope_freeze_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            freeze_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": freeze_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff = {
        "execution_envelope_freeze_proof_closeout_id": closeout_id,
        "frozen_envelope_verifier_handoff_id": handoff_id,
        "source_controlled_executor_quarantine_proof_closeout_id": source_closeout_id,
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout": (
            closeout_ready
        ),
        "execution_envelope_freeze_proof_closeout_ready": closeout_ready,
        "frozen_envelope_verifier_handoff_bound": closeout_ready,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "dry_run_execution_performed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "reads_secret_in_preview": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_execution_envelope_freeze_proof_closeout = {
        "execution_envelope_freeze_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_execution_envelope_freeze_proof_closeout"
        ),
        "source_controlled_executor_quarantine_proof_closeout_id": source_closeout_id,
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": (
            source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_id")
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": handoff_closeout.get(
            "no_execution_receipt_handoff_closeout_id"
        ),
        "source_no_execution_receipt_handoff_id": handoff.get("handoff_id"),
        "source_runner_invocation_boundary_closeout_id": boundary_closeout.get(
            "runner_invocation_boundary_closeout_id"
        ),
        "required_command_shape_hash": freeze_proof.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout": (
            closeout_ready
        ),
        "execution_envelope_freeze_proof_closeout_fields": freeze_closeout_fields,
        "execution_envelope_freeze_proof_closeout_field_count": len(
            freeze_closeout_fields
        ),
        "execution_envelope_freeze_proof_closeout_acceptance_gates": (
            freeze_closeout_acceptance_gates
        ),
        "execution_envelope_freeze_proof_closeout_acceptance_gate_count": len(
            freeze_closeout_acceptance_gates
        ),
        "frozen_envelope_verifier_handoff": frozen_envelope_verifier_handoff,
        "frozen_envelope_verifier_handoff_count": 1,
        "frozen_envelope_verifier_handoff_field_count": len(
            frozen_envelope_verifier_handoff_fields
        ),
        "dry_run_execution_envelope_freeze_proof": freeze_proof,
        "dry_run_execution_envelope_freeze_proof_count": 1,
        "controlled_executor_quarantine_proof_closeout": freeze_closeout,
        "controlled_executor_quarantine_proof_closeout_count": 1,
        "controlled_executor_quarantine_proof": quarantine,
        "controlled_executor_quarantine_proof_count": 1,
        "final_no_runner_execution_proof_closeout": source_quarantine_closeout,
        "final_no_runner_execution_proof_closeout_count": 1,
        "final_no_runner_execution_proof": final_proof,
        "final_no_runner_execution_proof_count": 1,
        "no_execution_receipt_handoff_closeout": handoff_closeout,
        "no_execution_receipt_handoff_closeout_count": 1,
        "target_file": freeze_closeout.get("target_file"),
        "expected_sha256": freeze_closeout.get("expected_sha256"),
        "actual_sha256": freeze_closeout.get("actual_sha256"),
        "hash_matches": freeze_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "execution_envelope_freeze_proof_closeout_only": True,
        "frozen_envelope_verifier_handoff_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_execution_envelope_freeze_proof_closeout_contract = {
        "mode": "controlled_dry_run_execution_envelope_freeze_proof_closeout_and_frozen_envelope_verifier_handoff_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-execution-envelope-freeze-proof-closeout"
        ),
        "source_controlled_executor_quarantine_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-controlled-executor-quarantine-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff": (
            closeout_ready
        ),
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_count": 1,
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_field_count": len(
                freeze_closeout_fields
            ),
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_acceptance_gate_count": len(
                freeze_closeout_acceptance_gates
            ),
            "frozen_envelope_verifier_handoff_count": 1,
            "frozen_envelope_verifier_handoff_field_count": len(
                frozen_envelope_verifier_handoff_fields
            ),
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(freeze_closeout_result.get("success")),
        "generated_at": freeze_closeout_result.get("generated_at"),
        "source_policy": freeze_closeout_result.get("policy"),
        "stats": freeze_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff": (
            future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff
        ),
        "controlled_dry_run_execution_envelope_freeze_proof_closeout": (
            controlled_dry_run_execution_envelope_freeze_proof_closeout
        ),
        "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract": (
            controlled_dry_run_execution_envelope_freeze_proof_closeout_contract
        ),
        "controlled_dry_run_execution_envelope_freeze_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_controlled_executor_quarantine_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract": (
            freeze_contract
        ),
        "source_controlled_dry_run_controlled_executor_quarantine_proof_closeout": (
            freeze_closeout
        ),
        "source_database_apply_controlled_dry_run_execution_envelope_freeze_proof": (
            future_freeze
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future frozen envelope verifier handoff closeout.",
            "Keep verifier invocation disabled until a later lane explicitly proves the verifier boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the verifier handoff while keeping verifier invocation locked."""
    handoff_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_handoff = (
        handoff_closeout_result.get(
            "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
        )
        or {}
    )
    handoff_closeout = (
        handoff_closeout_result.get(
            "controlled_dry_run_execution_envelope_freeze_proof_closeout"
        )
        or {}
    )
    handoff_contract = (
        handoff_closeout_result.get(
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
        )
        or {}
    )
    summary = handoff_closeout_result.get("summary") or {}
    safety = handoff_closeout_result.get("safety") or {}
    frozen_handoff = handoff_closeout.get("frozen_envelope_verifier_handoff") or {}
    freeze_proof = (
        handoff_closeout.get("dry_run_execution_envelope_freeze_proof") or {}
    )
    source_freeze_closeout = (
        handoff_closeout.get("controlled_executor_quarantine_proof_closeout") or {}
    )
    quarantine = handoff_closeout.get("controlled_executor_quarantine_proof") or {}
    source_quarantine_closeout = (
        handoff_closeout.get("final_no_runner_execution_proof_closeout") or {}
    )
    final_proof = handoff_closeout.get("final_no_runner_execution_proof") or {}
    handoff_receipt_closeout = (
        handoff_closeout.get("no_execution_receipt_handoff_closeout") or {}
    )
    rollback_binding = handoff_closeout.get("rollback_binding") or {}
    verifier_binding = handoff_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = handoff_closeout.get(
        "execution_envelope_freeze_proof_closeout_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_id(
            handoff_closeout_result
        )
    )
    lock_id = f"{closeout_id}-verifier-invocation-lock-proof"
    handoff_closeout_fields = [
        "frozen_envelope_verifier_handoff_closeout_id",
        "source_execution_envelope_freeze_proof_closeout_id",
        "source_frozen_envelope_verifier_handoff_id",
        "source_dry_run_execution_envelope_freeze_proof_id",
        "verifier_invocation_lock_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "verifier_invocation_locked",
        "verifier_invocation_allowed",
        "abort_conditions",
    ]
    handoff_closeout_acceptance_gates = [
        "execution_envelope_freeze_proof_closeout_ready",
        "source_chain_ids_match",
        "frozen_envelope_verifier_handoff_ready",
        "frozen_envelope_verifier_handoff_no_execute",
        "verifier_invocation_lock_proof_bound",
        "verifier_invocation_lock_proof_blocks_execution",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    verifier_invocation_lock_proof_fields = [
        "lock_proof_id",
        "source_frozen_envelope_verifier_handoff_closeout_id",
        "source_frozen_envelope_verifier_handoff_id",
        "source_execution_envelope_freeze_proof_closeout_id",
        "source_dry_run_execution_envelope_freeze_proof_id",
        "lock_mode",
        "verifier_invocation_locked",
        "verifier_invocation_allowed",
        "dry_run_executor_invocation_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_execution_envelope_freeze_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_frozen_envelope_verifier_handoff_missing",
        "abort_if_frozen_envelope_verifier_handoff_reports_execution",
        "abort_if_verifier_invocation_lock_proof_missing",
        "abort_if_verifier_invocation_is_allowed",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    verifier_invocation_lock_proof = {
        "lock_proof_id": lock_id,
        "source_frozen_envelope_verifier_handoff_closeout_id": closeout_id,
        "source_frozen_envelope_verifier_handoff_id": frozen_handoff.get(
            "handoff_id"
        ),
        "source_execution_envelope_freeze_proof_closeout_id": source_closeout_id,
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_closeout_id": (
            source_freeze_closeout.get("controlled_executor_quarantine_proof_closeout_id")
        ),
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": (
            source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_id")
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": (
            handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_id")
        ),
        "required_command_shape_hash": freeze_proof.get("required_command_shape_hash"),
        "lock_status": "verifier_invocation_lock_proof_preview_ready",
        "lock_mode": "verifier_invocation_lock_proof_preview_only",
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "ready_for_database_apply_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "verifier_invocation_lock_proof_field_count": len(
            verifier_invocation_lock_proof_fields
        ),
        "verifier_invocation_lock_proof_fields": verifier_invocation_lock_proof_fields,
    }
    handoff_closeout_ready = (
        handoff_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_handoff.get("execution_envelope_freeze_proof_closeout_id")
        == frozen_handoff.get("source_execution_envelope_freeze_proof_closeout_id")
        == verifier_invocation_lock_proof.get(
            "source_execution_envelope_freeze_proof_closeout_id"
        )
        and frozen_handoff.get("handoff_id")
        == future_handoff.get("frozen_envelope_verifier_handoff_id")
        == verifier_invocation_lock_proof.get(
            "source_frozen_envelope_verifier_handoff_id"
        )
        and freeze_proof.get("freeze_proof_id")
        == future_handoff.get("source_dry_run_execution_envelope_freeze_proof_id")
        == frozen_handoff.get("source_dry_run_execution_envelope_freeze_proof_id")
        == verifier_invocation_lock_proof.get(
            "source_dry_run_execution_envelope_freeze_proof_id"
        )
        and quarantine.get("quarantine_proof_id")
        == future_handoff.get("source_controlled_executor_quarantine_proof_id")
        == frozen_handoff.get("source_controlled_executor_quarantine_proof_id")
        == verifier_invocation_lock_proof.get(
            "source_controlled_executor_quarantine_proof_id"
        )
        and final_proof.get("proof_id")
        == frozen_handoff.get("source_final_no_runner_execution_proof_id")
        == verifier_invocation_lock_proof.get(
            "source_final_no_runner_execution_proof_id"
        )
        and handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_id")
        == frozen_handoff.get("source_no_execution_receipt_handoff_closeout_id")
        == verifier_invocation_lock_proof.get(
            "source_no_execution_receipt_handoff_closeout_id"
        )
    )
    frozen_envelope_verifier_handoff_ready = (
        handoff_closeout_ready
        and frozen_handoff.get("handoff_status")
        == "frozen_envelope_verifier_handoff_preview_ready"
        and frozen_handoff.get("handoff_id")
        == future_handoff.get("frozen_envelope_verifier_handoff_id")
        and int(
            frozen_handoff.get("frozen_envelope_verifier_handoff_field_count")
            or 0
        )
        == 12
        and summary.get("frozen_envelope_verifier_handoff_count") == 1
    )
    frozen_envelope_verifier_handoff_no_execute = (
        frozen_handoff.get("verifier_handoff_mode")
        == "frozen_envelope_verifier_handoff_preview_only"
        and frozen_handoff.get("execution_envelope_frozen") is True
        and frozen_handoff.get("execution_envelope_mutation_allowed") is False
        and frozen_handoff.get("verifier_invocation_allowed") is False
        and frozen_handoff.get("verifier_invoked") is False
        and frozen_handoff.get("verifier_receipt_present") is False
        and frozen_handoff.get("verifier_receipt_required") is False
        and frozen_handoff.get("dry_run_executor_invoked") is False
        and frozen_handoff.get("runner_invocation_performed") is False
        and frozen_handoff.get("endpoint_executed") is False
        and frozen_handoff.get("sql_executed") is False
        and frozen_handoff.get("database_written") is False
        and frozen_handoff.get("dry_run_executor_invocation_allowed") is False
        and frozen_handoff.get("runner_invocation_allowed") is False
        and frozen_handoff.get("ready_for_verifier_invocation_now") is False
        and frozen_handoff.get("ready_for_dry_run_executor_invocation_now") is False
        and frozen_handoff.get("ready_for_actual_dry_run_execution_now") is False
        and frozen_handoff.get("endpoint_execution_allowed") is False
        and frozen_handoff.get("sql_execution_allowed") is False
        and frozen_handoff.get("database_write_allowed") is False
        and frozen_handoff.get("database_apply_authorized") is False
        and frozen_handoff.get("executes_database_apply") is False
        and frozen_handoff.get("executes_endpoint") is False
        and frozen_handoff.get("executes_sql") is False
        and frozen_handoff.get("writes_database") is False
        and frozen_handoff.get("captures_stdout") is False
        and frozen_handoff.get("captures_stderr") is False
        and frozen_handoff.get("stdout_included") is False
        and frozen_handoff.get("stderr_included") is False
    )
    verifier_invocation_lock_proof_bound = (
        frozen_envelope_verifier_handoff_ready
        and bool(verifier_invocation_lock_proof.get("lock_proof_id"))
        and verifier_invocation_lock_proof.get(
            "source_frozen_envelope_verifier_handoff_closeout_id"
        )
        == closeout_id
        and verifier_invocation_lock_proof.get(
            "source_frozen_envelope_verifier_handoff_id"
        )
        == frozen_handoff.get("handoff_id")
        and verifier_invocation_lock_proof.get("required_command_shape_hash")
        == freeze_proof.get("required_command_shape_hash")
        and int(
            verifier_invocation_lock_proof.get(
                "verifier_invocation_lock_proof_field_count"
            )
            or 0
        )
        == len(verifier_invocation_lock_proof_fields)
    )
    verifier_invocation_lock_proof_blocks_execution = (
        verifier_invocation_lock_proof.get("lock_mode")
        == "verifier_invocation_lock_proof_preview_only"
        and verifier_invocation_lock_proof.get("verifier_invocation_locked") is True
        and verifier_invocation_lock_proof.get("verifier_invocation_allowed")
        is False
        and verifier_invocation_lock_proof.get("verifier_invoked") is False
        and verifier_invocation_lock_proof.get("verifier_receipt_present") is False
        and verifier_invocation_lock_proof.get("verifier_receipt_required") is False
        and verifier_invocation_lock_proof.get("dry_run_executor_invoked") is False
        and verifier_invocation_lock_proof.get("runner_invocation_performed")
        is False
        and verifier_invocation_lock_proof.get("endpoint_executed") is False
        and verifier_invocation_lock_proof.get("sql_executed") is False
        and verifier_invocation_lock_proof.get("database_written") is False
        and verifier_invocation_lock_proof.get("execution_receipt_present") is False
        and verifier_invocation_lock_proof.get("execution_receipt_required") is False
        and verifier_invocation_lock_proof.get("dry_run_executor_invocation_allowed")
        is False
        and verifier_invocation_lock_proof.get("runner_invocation_allowed") is False
        and verifier_invocation_lock_proof.get("ready_for_verifier_invocation_now")
        is False
        and verifier_invocation_lock_proof.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and verifier_invocation_lock_proof.get("ready_for_actual_dry_run_execution_now")
        is False
        and verifier_invocation_lock_proof.get("endpoint_execution_allowed") is False
        and verifier_invocation_lock_proof.get("sql_execution_allowed") is False
        and verifier_invocation_lock_proof.get("database_write_allowed") is False
        and verifier_invocation_lock_proof.get("database_apply_authorized") is False
        and verifier_invocation_lock_proof.get("executes_database_apply") is False
        and verifier_invocation_lock_proof.get("executes_endpoint") is False
        and verifier_invocation_lock_proof.get("executes_sql") is False
        and verifier_invocation_lock_proof.get("writes_database") is False
        and verifier_invocation_lock_proof.get("captures_stdout") is False
        and verifier_invocation_lock_proof.get("captures_stderr") is False
        and verifier_invocation_lock_proof.get("stdout_included") is False
        and verifier_invocation_lock_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        handoff_closeout.get("execution_envelope_freeze_proof_closeout_only") is True
        and handoff_closeout.get("frozen_envelope_verifier_handoff_only") is True
        and handoff_closeout.get("database_apply_authorized") is False
        and source_freeze_closeout.get("controlled_executor_quarantine_proof_closeout_only")
        is True
        and source_freeze_closeout.get("dry_run_execution_envelope_freeze_proof_only")
        is True
        and source_quarantine_closeout.get(
            "final_no_runner_execution_proof_closeout_only"
        )
        is True
        and handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_only")
        is True
        and frozen_envelope_verifier_handoff_no_execute
    )
    target_hash_locked = (
        handoff_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(handoff_closeout.get("expected_sha256"))
        and bool(handoff_closeout.get("actual_sha256"))
        and handoff_closeout.get("expected_sha256")
        == handoff_closeout.get("actual_sha256")
        and handoff_closeout.get("hash_matches") is True
        and handoff_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    handoff_contract_blocks_database_apply = (
        handoff_contract.get("executes_database_apply") is False
        and handoff_contract.get("executes_endpoint") is False
        and handoff_contract.get("executes_sql") is False
        and handoff_contract.get("database_apply_authorized") is False
        and handoff_contract.get("ready_for_database_apply_now") is False
        and handoff_contract.get("ready_for_verifier_invocation_now") is False
        and handoff_contract.get("ready_for_dry_run_executor_invocation_now") is False
        and handoff_contract.get("ready_for_actual_dry_run_execution_now") is False
        and handoff_contract.get("signs_database_apply_authorization") is False
        and handoff_contract.get("writes_database") is False
        and handoff_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("verifier_invoked_count", 0) == 0
        and summary.get("verifier_receipt_present_count", 0) == 0
        and summary.get("dry_run_executor_invoked_count", 0) == 0
        and summary.get("runner_invocation_performed_count", 0) == 0
        and summary.get("endpoint_executed_count", 0) == 0
        and summary.get("sql_executed_count", 0) == 0
        and summary.get("database_written_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and frozen_envelope_verifier_handoff_no_execute
        and verifier_invocation_lock_proof_blocks_execution
    )
    checks = [
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "execution_envelope_freeze_proof_closeout_ready",
            handoff_closeout_ready,
            {
                "result": handoff_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_execution_envelope_freeze_proof_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count"
                ),
            },
            "wait_for_execution_envelope_freeze_proof_closeout_ready",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "execution_envelope_freeze_proof_closeout_id": source_closeout_id,
                "frozen_envelope_verifier_handoff_id": frozen_handoff.get(
                    "handoff_id"
                ),
                "verifier_invocation_lock_proof_id": (
                    verifier_invocation_lock_proof.get("lock_proof_id")
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "frozen_envelope_verifier_handoff_ready",
            frozen_envelope_verifier_handoff_ready,
            {
                "handoff_id": frozen_handoff.get("handoff_id"),
                "handoff_status": frozen_handoff.get("handoff_status"),
                "field_count": frozen_handoff.get(
                    "frozen_envelope_verifier_handoff_field_count"
                ),
            },
            "wait_for_frozen_envelope_verifier_handoff_ready",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "frozen_envelope_verifier_handoff_no_execute",
            frozen_envelope_verifier_handoff_no_execute,
            {
                "verifier_handoff_mode": frozen_handoff.get(
                    "verifier_handoff_mode"
                ),
                "verifier_invocation_allowed": frozen_handoff.get(
                    "verifier_invocation_allowed"
                ),
                "verifier_invoked": frozen_handoff.get("verifier_invoked"),
            },
            "abort_if_frozen_envelope_verifier_handoff_reports_execution",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "verifier_invocation_lock_proof_bound",
            verifier_invocation_lock_proof_bound,
            {
                "lock_proof_id": verifier_invocation_lock_proof.get(
                    "lock_proof_id"
                ),
                "source_frozen_envelope_verifier_handoff_id": (
                    verifier_invocation_lock_proof.get(
                        "source_frozen_envelope_verifier_handoff_id"
                    )
                ),
                "field_count": verifier_invocation_lock_proof.get(
                    "verifier_invocation_lock_proof_field_count"
                ),
            },
            "wait_for_verifier_invocation_lock_proof_binding",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "verifier_invocation_lock_proof_blocks_execution",
            verifier_invocation_lock_proof_blocks_execution,
            {
                "lock_mode": verifier_invocation_lock_proof.get("lock_mode"),
                "verifier_invocation_locked": verifier_invocation_lock_proof.get(
                    "verifier_invocation_locked"
                ),
                "verifier_invocation_allowed": verifier_invocation_lock_proof.get(
                    "verifier_invocation_allowed"
                ),
            },
            "abort_if_verifier_invocation_lock_proof_allows_execution",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "execution_envelope_freeze_proof_closeout_only": (
                    handoff_closeout.get(
                        "execution_envelope_freeze_proof_closeout_only"
                    )
                ),
                "frozen_envelope_verifier_handoff_only": (
                    handoff_closeout.get("frozen_envelope_verifier_handoff_only")
                ),
                "lock_mode": verifier_invocation_lock_proof.get("lock_mode"),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": handoff_closeout.get("target_file"),
                "hash_matches": handoff_closeout.get("hash_matches"),
                "expected_sha256_present": bool(handoff_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(handoff_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "execution_envelope_freeze_proof_closeout_contract_blocks_database_apply",
            handoff_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff": (
                    handoff_contract.get(
                        "permits_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
                    )
                ),
                "database_apply_authorized": handoff_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": handoff_contract.get("writes_database"),
            },
            "abort_if_execution_envelope_freeze_proof_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "verifier_invoked_count": summary.get("verifier_invoked_count", 0),
                "signs_database_apply_authorization_count": summary.get(
                    "signs_database_apply_authorization_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check(
            "manual_review_not_required_for_safe_preview",
            handoff_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": handoff_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_verifier_invocation_lock_proof = {
        "frozen_envelope_verifier_handoff_closeout_id": closeout_id,
        "verifier_invocation_lock_proof_id": lock_id,
        "source_execution_envelope_freeze_proof_closeout_id": source_closeout_id,
        "source_frozen_envelope_verifier_handoff_id": frozen_handoff.get(
            "handoff_id"
        ),
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout": (
            closeout_ready
        ),
        "frozen_envelope_verifier_handoff_closeout_ready": closeout_ready,
        "execution_envelope_freeze_proof_closeout_ready": handoff_closeout_ready,
        "frozen_envelope_verifier_handoff_ready": (
            frozen_envelope_verifier_handoff_ready
        ),
        "verifier_invocation_lock_proof_bound": closeout_ready,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_frozen_envelope_verifier_handoff_closeout = {
        "frozen_envelope_verifier_handoff_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
        ),
        "source_execution_envelope_freeze_proof_closeout_id": source_closeout_id,
        "source_frozen_envelope_verifier_handoff_id": frozen_handoff.get(
            "handoff_id"
        ),
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_closeout_id": (
            source_freeze_closeout.get("controlled_executor_quarantine_proof_closeout_id")
        ),
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": (
            source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_id")
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": (
            handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_id")
        ),
        "required_command_shape_hash": freeze_proof.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
            closeout_ready
        ),
        "frozen_envelope_verifier_handoff_closeout_fields": (
            handoff_closeout_fields
        ),
        "frozen_envelope_verifier_handoff_closeout_field_count": len(
            handoff_closeout_fields
        ),
        "frozen_envelope_verifier_handoff_closeout_acceptance_gates": (
            handoff_closeout_acceptance_gates
        ),
        "frozen_envelope_verifier_handoff_closeout_acceptance_gate_count": len(
            handoff_closeout_acceptance_gates
        ),
        "verifier_invocation_lock_proof": verifier_invocation_lock_proof,
        "verifier_invocation_lock_proof_count": 1,
        "verifier_invocation_lock_proof_field_count": len(
            verifier_invocation_lock_proof_fields
        ),
        "frozen_envelope_verifier_handoff": frozen_handoff,
        "frozen_envelope_verifier_handoff_count": 1,
        "frozen_envelope_verifier_handoff_field_count": int(
            frozen_handoff.get("frozen_envelope_verifier_handoff_field_count") or 0
        ),
        "dry_run_execution_envelope_freeze_proof": freeze_proof,
        "dry_run_execution_envelope_freeze_proof_count": 1,
        "execution_envelope_freeze_proof_closeout": handoff_closeout,
        "execution_envelope_freeze_proof_closeout_count": 1,
        "controlled_executor_quarantine_proof_closeout": source_freeze_closeout,
        "controlled_executor_quarantine_proof_closeout_count": 1,
        "controlled_executor_quarantine_proof": quarantine,
        "controlled_executor_quarantine_proof_count": 1,
        "final_no_runner_execution_proof_closeout": source_quarantine_closeout,
        "final_no_runner_execution_proof_closeout_count": 1,
        "final_no_runner_execution_proof": final_proof,
        "final_no_runner_execution_proof_count": 1,
        "no_execution_receipt_handoff_closeout": handoff_receipt_closeout,
        "no_execution_receipt_handoff_closeout_count": 1,
        "target_file": handoff_closeout.get("target_file"),
        "expected_sha256": handoff_closeout.get("expected_sha256"),
        "actual_sha256": handoff_closeout.get("actual_sha256"),
        "hash_matches": handoff_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "frozen_envelope_verifier_handoff_closeout_only": True,
        "verifier_invocation_lock_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract = {
        "mode": "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_and_verifier_invocation_lock_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-frozen-envelope-verifier-handoff-closeout"
        ),
        "source_execution_envelope_freeze_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-execution-envelope-freeze-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
            closeout_ready
        ),
        "verifier_invocation_locked": True,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_count": 1,
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_field_count": len(
                handoff_closeout_fields
            ),
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_acceptance_gate_count": len(
                handoff_closeout_acceptance_gates
            ),
            "verifier_invocation_lock_proof_count": 1,
            "verifier_invocation_lock_proof_field_count": len(
                verifier_invocation_lock_proof_fields
            ),
            "verifier_invocation_locked_count": 1,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(handoff_closeout_result.get("success")),
        "generated_at": handoff_closeout_result.get("generated_at"),
        "source_policy": handoff_closeout_result.get("policy"),
        "stats": handoff_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
            future_database_apply_controlled_dry_run_verifier_invocation_lock_proof
        ),
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout": (
            controlled_dry_run_frozen_envelope_verifier_handoff_closeout
        ),
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract": (
            controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract
        ),
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_checks": checks,
        "source_controlled_dry_run_execution_envelope_freeze_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_execution_envelope_freeze_proof_closeout_contract": (
            handoff_contract
        ),
        "source_controlled_dry_run_execution_envelope_freeze_proof_closeout": (
            handoff_closeout
        ),
        "source_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff": (
            future_handoff
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future verifier invocation lock proof closeout.",
            "Keep verifier invocation disabled until a later no-execution receipt proof closes this lock boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, verifier invocation, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the verifier invocation lock and prove no verifier receipt exists."""
    lock_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_lock = (
        lock_closeout_result.get(
            "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
        )
        or {}
    )
    lock_closeout = (
        lock_closeout_result.get(
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
        )
        or {}
    )
    lock_contract = (
        lock_closeout_result.get(
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
        )
        or {}
    )
    summary = lock_closeout_result.get("summary") or {}
    safety = lock_closeout_result.get("safety") or {}
    lock_proof = lock_closeout.get("verifier_invocation_lock_proof") or {}
    frozen_handoff = lock_closeout.get("frozen_envelope_verifier_handoff") or {}
    source_handoff_closeout = (
        lock_closeout.get("execution_envelope_freeze_proof_closeout") or {}
    )
    freeze_proof = (
        lock_closeout.get("dry_run_execution_envelope_freeze_proof") or {}
    )
    source_freeze_closeout = (
        lock_closeout.get("controlled_executor_quarantine_proof_closeout") or {}
    )
    quarantine = lock_closeout.get("controlled_executor_quarantine_proof") or {}
    source_quarantine_closeout = (
        lock_closeout.get("final_no_runner_execution_proof_closeout") or {}
    )
    final_proof = lock_closeout.get("final_no_runner_execution_proof") or {}
    handoff_receipt_closeout = (
        lock_closeout.get("no_execution_receipt_handoff_closeout") or {}
    )
    rollback_binding = lock_closeout.get("rollback_binding") or {}
    verifier_binding = lock_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = lock_closeout.get(
        "frozen_envelope_verifier_handoff_closeout_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout_id(
            lock_closeout_result
        )
    )
    receipt_id = f"{closeout_id}-verifier-no-execution-receipt-proof"
    lock_closeout_fields = [
        "verifier_invocation_lock_proof_closeout_id",
        "source_frozen_envelope_verifier_handoff_closeout_id",
        "source_verifier_invocation_lock_proof_id",
        "source_frozen_envelope_verifier_handoff_id",
        "verifier_no_execution_receipt_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "verifier_invocation_locked",
        "verifier_invoked",
        "abort_conditions",
    ]
    lock_closeout_acceptance_gates = [
        "frozen_envelope_verifier_handoff_closeout_ready",
        "source_chain_ids_match",
        "verifier_invocation_lock_proof_ready",
        "verifier_invocation_lock_proof_no_execute",
        "verifier_no_execution_receipt_proof_bound",
        "verifier_no_execution_receipt_proof_blocks_execution",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_or_database_apply",
    ]
    verifier_no_execution_receipt_proof_fields = [
        "receipt_proof_id",
        "source_verifier_invocation_lock_proof_closeout_id",
        "source_verifier_invocation_lock_proof_id",
        "source_frozen_envelope_verifier_handoff_closeout_id",
        "source_frozen_envelope_verifier_handoff_id",
        "receipt_mode",
        "verifier_invocation_locked",
        "verifier_invoked",
        "verifier_receipt_present",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_frozen_envelope_verifier_handoff_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_verifier_invocation_lock_proof_missing",
        "abort_if_verifier_invocation_lock_proof_reports_execution",
        "abort_if_verifier_no_execution_receipt_proof_missing",
        "abort_if_verifier_receipt_is_present",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_or_apply_material_is_present",
    ]
    verifier_no_execution_receipt_proof = {
        "receipt_proof_id": receipt_id,
        "source_verifier_invocation_lock_proof_closeout_id": closeout_id,
        "source_verifier_invocation_lock_proof_id": lock_proof.get("lock_proof_id"),
        "source_frozen_envelope_verifier_handoff_closeout_id": source_closeout_id,
        "source_frozen_envelope_verifier_handoff_id": frozen_handoff.get(
            "handoff_id"
        ),
        "source_execution_envelope_freeze_proof_closeout_id": (
            source_handoff_closeout.get("execution_envelope_freeze_proof_closeout_id")
        ),
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_closeout_id": (
            source_freeze_closeout.get("controlled_executor_quarantine_proof_closeout_id")
        ),
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": (
            source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_id")
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": (
            handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_id")
        ),
        "required_command_shape_hash": freeze_proof.get("required_command_shape_hash"),
        "receipt_status": "verifier_no_execution_receipt_proof_preview_ready",
        "receipt_mode": "verifier_no_execution_receipt_proof_preview_only",
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "execution_receipt_required": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "ready_for_database_apply_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "verifier_no_execution_receipt_proof_field_count": len(
            verifier_no_execution_receipt_proof_fields
        ),
        "verifier_no_execution_receipt_proof_fields": (
            verifier_no_execution_receipt_proof_fields
        ),
    }
    lock_closeout_ready = (
        lock_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_lock.get("frozen_envelope_verifier_handoff_closeout_id")
        == lock_proof.get("source_frozen_envelope_verifier_handoff_closeout_id")
        == verifier_no_execution_receipt_proof.get(
            "source_frozen_envelope_verifier_handoff_closeout_id"
        )
        and lock_proof.get("lock_proof_id")
        == future_lock.get("verifier_invocation_lock_proof_id")
        == verifier_no_execution_receipt_proof.get(
            "source_verifier_invocation_lock_proof_id"
        )
        and frozen_handoff.get("handoff_id")
        == future_lock.get("source_frozen_envelope_verifier_handoff_id")
        == lock_proof.get("source_frozen_envelope_verifier_handoff_id")
        == verifier_no_execution_receipt_proof.get(
            "source_frozen_envelope_verifier_handoff_id"
        )
        and source_handoff_closeout.get("execution_envelope_freeze_proof_closeout_id")
        == future_lock.get("source_execution_envelope_freeze_proof_closeout_id")
        == lock_proof.get("source_execution_envelope_freeze_proof_closeout_id")
        == verifier_no_execution_receipt_proof.get(
            "source_execution_envelope_freeze_proof_closeout_id"
        )
        and freeze_proof.get("freeze_proof_id")
        == future_lock.get("source_dry_run_execution_envelope_freeze_proof_id")
        == lock_proof.get("source_dry_run_execution_envelope_freeze_proof_id")
        == verifier_no_execution_receipt_proof.get(
            "source_dry_run_execution_envelope_freeze_proof_id"
        )
        and quarantine.get("quarantine_proof_id")
        == lock_proof.get("source_controlled_executor_quarantine_proof_id")
        == verifier_no_execution_receipt_proof.get(
            "source_controlled_executor_quarantine_proof_id"
        )
        and final_proof.get("proof_id")
        == lock_proof.get("source_final_no_runner_execution_proof_id")
        == verifier_no_execution_receipt_proof.get(
            "source_final_no_runner_execution_proof_id"
        )
        and handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_id")
        == lock_proof.get("source_no_execution_receipt_handoff_closeout_id")
        == verifier_no_execution_receipt_proof.get(
            "source_no_execution_receipt_handoff_closeout_id"
        )
    )
    verifier_invocation_lock_proof_ready = (
        lock_closeout_ready
        and lock_proof.get("lock_status")
        == "verifier_invocation_lock_proof_preview_ready"
        and lock_proof.get("lock_proof_id")
        == future_lock.get("verifier_invocation_lock_proof_id")
        and int(lock_proof.get("verifier_invocation_lock_proof_field_count") or 0)
        == 12
        and summary.get("verifier_invocation_lock_proof_count") == 1
    )
    verifier_invocation_lock_proof_no_execute = (
        lock_proof.get("lock_mode") == "verifier_invocation_lock_proof_preview_only"
        and lock_proof.get("verifier_invocation_locked") is True
        and lock_proof.get("verifier_invocation_allowed") is False
        and lock_proof.get("verifier_invoked") is False
        and lock_proof.get("verifier_receipt_present") is False
        and lock_proof.get("verifier_receipt_required") is False
        and lock_proof.get("dry_run_executor_invoked") is False
        and lock_proof.get("runner_invocation_performed") is False
        and lock_proof.get("endpoint_executed") is False
        and lock_proof.get("sql_executed") is False
        and lock_proof.get("database_written") is False
        and lock_proof.get("execution_receipt_present") is False
        and lock_proof.get("execution_receipt_required") is False
        and lock_proof.get("dry_run_executor_invocation_allowed") is False
        and lock_proof.get("runner_invocation_allowed") is False
        and lock_proof.get("ready_for_verifier_invocation_now") is False
        and lock_proof.get("ready_for_dry_run_executor_invocation_now") is False
        and lock_proof.get("ready_for_actual_dry_run_execution_now") is False
        and lock_proof.get("endpoint_execution_allowed") is False
        and lock_proof.get("sql_execution_allowed") is False
        and lock_proof.get("database_write_allowed") is False
        and lock_proof.get("database_apply_authorized") is False
        and lock_proof.get("executes_database_apply") is False
        and lock_proof.get("executes_endpoint") is False
        and lock_proof.get("executes_sql") is False
        and lock_proof.get("writes_database") is False
        and lock_proof.get("captures_stdout") is False
        and lock_proof.get("captures_stderr") is False
        and lock_proof.get("stdout_included") is False
        and lock_proof.get("stderr_included") is False
    )
    verifier_no_execution_receipt_proof_bound = (
        verifier_invocation_lock_proof_ready
        and bool(verifier_no_execution_receipt_proof.get("receipt_proof_id"))
        and verifier_no_execution_receipt_proof.get(
            "source_verifier_invocation_lock_proof_closeout_id"
        )
        == closeout_id
        and verifier_no_execution_receipt_proof.get(
            "source_verifier_invocation_lock_proof_id"
        )
        == lock_proof.get("lock_proof_id")
        and verifier_no_execution_receipt_proof.get("required_command_shape_hash")
        == freeze_proof.get("required_command_shape_hash")
        and int(
            verifier_no_execution_receipt_proof.get(
                "verifier_no_execution_receipt_proof_field_count"
            )
            or 0
        )
        == len(verifier_no_execution_receipt_proof_fields)
    )
    verifier_no_execution_receipt_proof_blocks_execution = (
        verifier_no_execution_receipt_proof.get("receipt_mode")
        == "verifier_no_execution_receipt_proof_preview_only"
        and verifier_no_execution_receipt_proof.get("verifier_invocation_locked")
        is True
        and verifier_no_execution_receipt_proof.get("verifier_invocation_allowed")
        is False
        and verifier_no_execution_receipt_proof.get("verifier_invoked") is False
        and verifier_no_execution_receipt_proof.get("verifier_receipt_present")
        is False
        and verifier_no_execution_receipt_proof.get("verifier_receipt_required")
        is False
        and verifier_no_execution_receipt_proof.get("dry_run_executor_invoked")
        is False
        and verifier_no_execution_receipt_proof.get("runner_invocation_performed")
        is False
        and verifier_no_execution_receipt_proof.get("endpoint_executed") is False
        and verifier_no_execution_receipt_proof.get("sql_executed") is False
        and verifier_no_execution_receipt_proof.get("database_written") is False
        and verifier_no_execution_receipt_proof.get("execution_receipt_present")
        is False
        and verifier_no_execution_receipt_proof.get("execution_receipt_required")
        is False
        and verifier_no_execution_receipt_proof.get(
            "dry_run_executor_invocation_allowed"
        )
        is False
        and verifier_no_execution_receipt_proof.get("runner_invocation_allowed")
        is False
        and verifier_no_execution_receipt_proof.get(
            "ready_for_verifier_invocation_now"
        )
        is False
        and verifier_no_execution_receipt_proof.get(
            "ready_for_dry_run_executor_invocation_now"
        )
        is False
        and verifier_no_execution_receipt_proof.get(
            "ready_for_actual_dry_run_execution_now"
        )
        is False
        and verifier_no_execution_receipt_proof.get("endpoint_execution_allowed")
        is False
        and verifier_no_execution_receipt_proof.get("sql_execution_allowed") is False
        and verifier_no_execution_receipt_proof.get("database_write_allowed") is False
        and verifier_no_execution_receipt_proof.get("database_apply_authorized")
        is False
        and verifier_no_execution_receipt_proof.get("executes_database_apply")
        is False
        and verifier_no_execution_receipt_proof.get("executes_endpoint") is False
        and verifier_no_execution_receipt_proof.get("executes_sql") is False
        and verifier_no_execution_receipt_proof.get("writes_database") is False
        and verifier_no_execution_receipt_proof.get("captures_stdout") is False
        and verifier_no_execution_receipt_proof.get("captures_stderr") is False
        and verifier_no_execution_receipt_proof.get("stdout_included") is False
        and verifier_no_execution_receipt_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        lock_closeout.get("frozen_envelope_verifier_handoff_closeout_only") is True
        and lock_closeout.get("verifier_invocation_lock_proof_only") is True
        and lock_closeout.get("database_apply_authorized") is False
        and source_handoff_closeout.get("execution_envelope_freeze_proof_closeout_only")
        is True
        and source_handoff_closeout.get("frozen_envelope_verifier_handoff_only")
        is True
        and source_freeze_closeout.get("controlled_executor_quarantine_proof_closeout_only")
        is True
        and handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_only")
        is True
        and verifier_invocation_lock_proof_no_execute
    )
    target_hash_locked = (
        lock_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(lock_closeout.get("expected_sha256"))
        and bool(lock_closeout.get("actual_sha256"))
        and lock_closeout.get("expected_sha256") == lock_closeout.get("actual_sha256")
        and lock_closeout.get("hash_matches") is True
        and lock_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    lock_contract_blocks_database_apply = (
        lock_contract.get("executes_database_apply") is False
        and lock_contract.get("executes_endpoint") is False
        and lock_contract.get("executes_sql") is False
        and lock_contract.get("database_apply_authorized") is False
        and lock_contract.get("ready_for_database_apply_now") is False
        and lock_contract.get("ready_for_verifier_invocation_now") is False
        and lock_contract.get("ready_for_dry_run_executor_invocation_now") is False
        and lock_contract.get("ready_for_actual_dry_run_execution_now") is False
        and lock_contract.get("signs_database_apply_authorization") is False
        and lock_contract.get("writes_database") is False
        and lock_contract.get("executes_in_preview") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_script_count", 0) == 0
        and summary.get("executes_migration_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("verifier_invoked_count", 0) == 0
        and summary.get("verifier_receipt_present_count", 0) == 0
        and summary.get("dry_run_executor_invoked_count", 0) == 0
        and summary.get("runner_invocation_performed_count", 0) == 0
        and summary.get("endpoint_executed_count", 0) == 0
        and summary.get("sql_executed_count", 0) == 0
        and summary.get("database_written_count", 0) == 0
        and safety.get("reads_secret_in_preview") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
        and verifier_invocation_lock_proof_no_execute
        and verifier_no_execution_receipt_proof_blocks_execution
    )
    checks = [
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "frozen_envelope_verifier_handoff_closeout_ready",
            lock_closeout_ready,
            {
                "result": lock_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count"
                ),
                "pass_count": summary.get(
                    "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_pass_count"
                ),
                "check_count": summary.get(
                    "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count"
                ),
            },
            "wait_for_frozen_envelope_verifier_handoff_closeout_ready",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "frozen_envelope_verifier_handoff_closeout_id": source_closeout_id,
                "verifier_invocation_lock_proof_id": lock_proof.get(
                    "lock_proof_id"
                ),
                "verifier_no_execution_receipt_proof_id": (
                    verifier_no_execution_receipt_proof.get("receipt_proof_id")
                ),
            },
            "wait_for_source_chain_ids_match",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "verifier_invocation_lock_proof_ready",
            verifier_invocation_lock_proof_ready,
            {
                "lock_proof_id": lock_proof.get("lock_proof_id"),
                "lock_status": lock_proof.get("lock_status"),
                "field_count": lock_proof.get(
                    "verifier_invocation_lock_proof_field_count"
                ),
            },
            "wait_for_verifier_invocation_lock_proof_ready",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "verifier_invocation_lock_proof_no_execute",
            verifier_invocation_lock_proof_no_execute,
            {
                "lock_mode": lock_proof.get("lock_mode"),
                "verifier_invocation_locked": lock_proof.get(
                    "verifier_invocation_locked"
                ),
                "verifier_invoked": lock_proof.get("verifier_invoked"),
            },
            "abort_if_verifier_invocation_lock_proof_reports_execution",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "verifier_no_execution_receipt_proof_bound",
            verifier_no_execution_receipt_proof_bound,
            {
                "receipt_proof_id": verifier_no_execution_receipt_proof.get(
                    "receipt_proof_id"
                ),
                "source_verifier_invocation_lock_proof_id": (
                    verifier_no_execution_receipt_proof.get(
                        "source_verifier_invocation_lock_proof_id"
                    )
                ),
                "field_count": verifier_no_execution_receipt_proof.get(
                    "verifier_no_execution_receipt_proof_field_count"
                ),
            },
            "wait_for_verifier_no_execution_receipt_proof_binding",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "verifier_no_execution_receipt_proof_blocks_execution",
            verifier_no_execution_receipt_proof_blocks_execution,
            {
                "receipt_mode": verifier_no_execution_receipt_proof.get(
                    "receipt_mode"
                ),
                "verifier_invoked": verifier_no_execution_receipt_proof.get(
                    "verifier_invoked"
                ),
                "verifier_receipt_present": verifier_no_execution_receipt_proof.get(
                    "verifier_receipt_present"
                ),
            },
            "abort_if_verifier_no_execution_receipt_proof_allows_execution",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "frozen_envelope_verifier_handoff_closeout_only": (
                    lock_closeout.get("frozen_envelope_verifier_handoff_closeout_only")
                ),
                "verifier_invocation_lock_proof_only": (
                    lock_closeout.get("verifier_invocation_lock_proof_only")
                ),
                "receipt_mode": verifier_no_execution_receipt_proof.get(
                    "receipt_mode"
                ),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": lock_closeout.get("target_file"),
                "hash_matches": lock_closeout.get("hash_matches"),
                "expected_sha256_present": bool(lock_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(lock_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
                "database_apply_authorized": verifier_binding.get(
                    "database_apply_authorized"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "frozen_envelope_verifier_handoff_closeout_contract_blocks_database_apply",
            lock_contract_blocks_database_apply,
            {
                "permits_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
                    lock_contract.get(
                        "permits_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
                    )
                ),
                "database_apply_authorized": lock_contract.get(
                    "database_apply_authorized"
                ),
                "writes_database": lock_contract.get("writes_database"),
            },
            "abort_if_frozen_envelope_verifier_handoff_closeout_contract_authorizes_database_apply",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "preview_has_no_side_effects_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "verifier_invoked_count": summary.get("verifier_invoked_count", 0),
                "verifier_receipt_present_count": summary.get(
                    "verifier_receipt_present_count", 0
                ),
            },
            "abort_on_preview_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_verifier_invocation_lock_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            lock_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": lock_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof = {
        "verifier_invocation_lock_proof_closeout_id": closeout_id,
        "verifier_no_execution_receipt_proof_id": receipt_id,
        "source_frozen_envelope_verifier_handoff_closeout_id": source_closeout_id,
        "source_verifier_invocation_lock_proof_id": lock_proof.get("lock_proof_id"),
        "source_frozen_envelope_verifier_handoff_id": frozen_handoff.get(
            "handoff_id"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout": (
            closeout_ready
        ),
        "verifier_invocation_lock_proof_closeout_ready": closeout_ready,
        "frozen_envelope_verifier_handoff_closeout_ready": lock_closeout_ready,
        "verifier_invocation_lock_proof_ready": verifier_invocation_lock_proof_ready,
        "verifier_no_execution_receipt_proof_bound": closeout_ready,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_verifier_invocation_lock_proof_closeout = {
        "verifier_invocation_lock_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_verifier_invocation_lock_proof_closeout"
        ),
        "source_frozen_envelope_verifier_handoff_closeout_id": source_closeout_id,
        "source_verifier_invocation_lock_proof_id": lock_proof.get("lock_proof_id"),
        "source_frozen_envelope_verifier_handoff_id": frozen_handoff.get(
            "handoff_id"
        ),
        "source_execution_envelope_freeze_proof_closeout_id": (
            source_handoff_closeout.get("execution_envelope_freeze_proof_closeout_id")
        ),
        "source_dry_run_execution_envelope_freeze_proof_id": freeze_proof.get(
            "freeze_proof_id"
        ),
        "source_controlled_executor_quarantine_proof_closeout_id": (
            source_freeze_closeout.get("controlled_executor_quarantine_proof_closeout_id")
        ),
        "source_controlled_executor_quarantine_proof_id": quarantine.get(
            "quarantine_proof_id"
        ),
        "source_final_no_runner_execution_proof_closeout_id": (
            source_quarantine_closeout.get("final_no_runner_execution_proof_closeout_id")
        ),
        "source_final_no_runner_execution_proof_id": final_proof.get("proof_id"),
        "source_no_execution_receipt_handoff_closeout_id": (
            handoff_receipt_closeout.get("no_execution_receipt_handoff_closeout_id")
        ),
        "required_command_shape_hash": freeze_proof.get("required_command_shape_hash"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof": (
            closeout_ready
        ),
        "verifier_invocation_lock_proof_closeout_fields": lock_closeout_fields,
        "verifier_invocation_lock_proof_closeout_field_count": len(
            lock_closeout_fields
        ),
        "verifier_invocation_lock_proof_closeout_acceptance_gates": (
            lock_closeout_acceptance_gates
        ),
        "verifier_invocation_lock_proof_closeout_acceptance_gate_count": len(
            lock_closeout_acceptance_gates
        ),
        "verifier_no_execution_receipt_proof": verifier_no_execution_receipt_proof,
        "verifier_no_execution_receipt_proof_count": 1,
        "verifier_no_execution_receipt_proof_field_count": len(
            verifier_no_execution_receipt_proof_fields
        ),
        "verifier_invocation_lock_proof": lock_proof,
        "verifier_invocation_lock_proof_count": 1,
        "verifier_invocation_lock_proof_field_count": int(
            lock_proof.get("verifier_invocation_lock_proof_field_count") or 0
        ),
        "frozen_envelope_verifier_handoff_closeout": lock_closeout,
        "frozen_envelope_verifier_handoff_closeout_count": 1,
        "frozen_envelope_verifier_handoff": frozen_handoff,
        "frozen_envelope_verifier_handoff_count": 1,
        "dry_run_execution_envelope_freeze_proof": freeze_proof,
        "dry_run_execution_envelope_freeze_proof_count": 1,
        "execution_envelope_freeze_proof_closeout": source_handoff_closeout,
        "execution_envelope_freeze_proof_closeout_count": 1,
        "controlled_executor_quarantine_proof_closeout": source_freeze_closeout,
        "controlled_executor_quarantine_proof_closeout_count": 1,
        "controlled_executor_quarantine_proof": quarantine,
        "controlled_executor_quarantine_proof_count": 1,
        "final_no_runner_execution_proof_closeout": source_quarantine_closeout,
        "final_no_runner_execution_proof_closeout_count": 1,
        "final_no_runner_execution_proof": final_proof,
        "final_no_runner_execution_proof_count": 1,
        "no_execution_receipt_handoff_closeout": handoff_receipt_closeout,
        "no_execution_receipt_handoff_closeout_count": 1,
        "target_file": lock_closeout.get("target_file"),
        "expected_sha256": lock_closeout.get("expected_sha256"),
        "actual_sha256": lock_closeout.get("actual_sha256"),
        "hash_matches": lock_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "verifier_invocation_lock_proof_closeout_only": True,
        "verifier_no_execution_receipt_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "controlled_executor_quarantine_bound": True,
        "executor_quarantine_enforced": True,
        "execution_envelope_frozen": True,
        "execution_envelope_mutation_allowed": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_verifier_invocation_lock_proof_closeout_contract = {
        "mode": "controlled_dry_run_verifier_invocation_lock_proof_closeout_and_verifier_no_execution_receipt_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-verifier-invocation-lock-proof-closeout"
        ),
        "source_frozen_envelope_verifier_handoff_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-frozen-envelope-verifier-handoff-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof": (
            closeout_ready
        ),
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "persists_verifier_receipt": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_count": 1,
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_field_count": len(
                lock_closeout_fields
            ),
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_acceptance_gate_count": len(
                lock_closeout_acceptance_gates
            ),
            "verifier_no_execution_receipt_proof_count": 1,
            "verifier_no_execution_receipt_proof_field_count": len(
                verifier_no_execution_receipt_proof_fields
            ),
            "verifier_invocation_locked_count": 1,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(lock_closeout_result.get("success")),
        "generated_at": lock_closeout_result.get("generated_at"),
        "source_policy": lock_closeout_result.get("policy"),
        "stats": lock_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof": (
            future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof
        ),
        "controlled_dry_run_verifier_invocation_lock_proof_closeout": (
            controlled_dry_run_verifier_invocation_lock_proof_closeout
        ),
        "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract": (
            controlled_dry_run_verifier_invocation_lock_proof_closeout_contract
        ),
        "controlled_dry_run_verifier_invocation_lock_proof_closeout_checks": checks,
        "source_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract": (
            lock_contract
        ),
        "source_controlled_dry_run_frozen_envelope_verifier_handoff_closeout": (
            lock_closeout
        ),
        "source_database_apply_controlled_dry_run_verifier_invocation_lock_proof": (
            future_lock
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future verifier no-execution receipt proof closeout.",
            "Keep verifier invocation and verifier receipt persistence disabled until a later lane explicitly proves that boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, verifier invocation, verifier receipt persistence, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the no-execution receipt proof and keep receipt persistence locked."""
    receipt_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_receipt = (
        receipt_closeout_result.get(
            "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        )
        or {}
    )
    receipt_closeout = (
        receipt_closeout_result.get(
            "controlled_dry_run_verifier_invocation_lock_proof_closeout"
        )
        or {}
    )
    receipt_contract = (
        receipt_closeout_result.get(
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract"
        )
        or {}
    )
    summary = receipt_closeout_result.get("summary") or {}
    safety = receipt_closeout_result.get("safety") or {}
    receipt_proof = receipt_closeout.get("verifier_no_execution_receipt_proof") or {}
    lock_proof = receipt_closeout.get("verifier_invocation_lock_proof") or {}
    previous_lock_closeout = (
        receipt_closeout.get("frozen_envelope_verifier_handoff_closeout") or {}
    )
    rollback_binding = receipt_closeout.get("rollback_binding") or {}
    verifier_binding = receipt_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = receipt_closeout.get(
        "verifier_invocation_lock_proof_closeout_id"
    )
    source_receipt_id = receipt_proof.get("receipt_proof_id")
    closeout_id = (
        _db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_id(
            receipt_closeout_result
        )
    )
    guard_id = f"{closeout_id}-verifier-receipt-persistence-guard-proof"
    closeout_fields = [
        "verifier_no_execution_receipt_proof_closeout_id",
        "source_verifier_invocation_lock_proof_closeout_id",
        "source_verifier_no_execution_receipt_proof_id",
        "source_verifier_invocation_lock_proof_id",
        "verifier_receipt_persistence_guard_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "verifier_receipt_persistence_locked",
        "verifier_receipt_persisted",
        "abort_conditions",
    ]
    acceptance_gates = [
        "verifier_invocation_lock_proof_closeout_ready",
        "source_chain_ids_match",
        "verifier_no_execution_receipt_proof_ready",
        "verifier_no_execution_receipt_proof_no_execute",
        "verifier_receipt_persistence_guard_proof_bound",
        "verifier_receipt_persistence_guard_proof_blocks_persistence",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_persistence_or_database_apply",
    ]
    persistence_guard_fields = [
        "guard_proof_id",
        "source_verifier_no_execution_receipt_proof_closeout_id",
        "source_verifier_invocation_lock_proof_closeout_id",
        "source_verifier_no_execution_receipt_proof_id",
        "source_verifier_invocation_lock_proof_id",
        "guard_mode",
        "verifier_receipt_persistence_locked",
        "verifier_receipt_persisted",
        "verifier_receipt_persistence_allowed",
        "endpoint_execution_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_verifier_invocation_lock_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_verifier_no_execution_receipt_proof_missing",
        "abort_if_verifier_no_execution_receipt_proof_reports_execution",
        "abort_if_verifier_receipt_persistence_guard_missing",
        "abort_if_verifier_receipt_persistence_is_allowed",
        "abort_if_verifier_receipt_is_persisted",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_persistence_or_apply_material_is_present",
    ]
    persistence_guard_proof = {
        "guard_proof_id": guard_id,
        "source_verifier_no_execution_receipt_proof_closeout_id": closeout_id,
        "source_verifier_invocation_lock_proof_closeout_id": source_closeout_id,
        "source_verifier_no_execution_receipt_proof_id": source_receipt_id,
        "source_verifier_invocation_lock_proof_id": lock_proof.get("lock_proof_id"),
        "source_frozen_envelope_verifier_handoff_closeout_id": (
            receipt_proof.get("source_frozen_envelope_verifier_handoff_closeout_id")
        ),
        "source_frozen_envelope_verifier_handoff_id": (
            receipt_proof.get("source_frozen_envelope_verifier_handoff_id")
        ),
        "required_command_shape_hash": receipt_proof.get(
            "required_command_shape_hash"
        ),
        "guard_status": "verifier_receipt_persistence_guard_proof_preview_ready",
        "guard_mode": "verifier_receipt_persistence_guard_proof_preview_only",
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "persists_verifier_receipt": False,
        "persistence_receipt_present": False,
        "persistence_receipt_required": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "verifier_receipt_persistence_guard_proof_field_count": len(
            persistence_guard_fields
        ),
        "verifier_receipt_persistence_guard_proof_fields": (
            persistence_guard_fields
        ),
    }
    receipt_closeout_ready = (
        receipt_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_receipt.get("verifier_invocation_lock_proof_closeout_id")
        == receipt_proof.get("source_verifier_invocation_lock_proof_closeout_id")
        == persistence_guard_proof.get(
            "source_verifier_invocation_lock_proof_closeout_id"
        )
        and source_receipt_id
        == future_receipt.get("verifier_no_execution_receipt_proof_id")
        == persistence_guard_proof.get(
            "source_verifier_no_execution_receipt_proof_id"
        )
        and lock_proof.get("lock_proof_id")
        == receipt_proof.get("source_verifier_invocation_lock_proof_id")
        == persistence_guard_proof.get(
            "source_verifier_invocation_lock_proof_id"
        )
        and receipt_proof.get("required_command_shape_hash")
        == lock_proof.get("required_command_shape_hash")
        == persistence_guard_proof.get("required_command_shape_hash")
    )
    receipt_proof_ready = (
        receipt_closeout_ready
        and receipt_proof.get("receipt_status")
        == "verifier_no_execution_receipt_proof_preview_ready"
        and receipt_proof.get("receipt_proof_id")
        == future_receipt.get("verifier_no_execution_receipt_proof_id")
        and int(
            receipt_proof.get("verifier_no_execution_receipt_proof_field_count")
            or 0
        )
        == 12
        and summary.get("verifier_no_execution_receipt_proof_count") == 1
    )
    receipt_proof_no_execute = (
        receipt_proof.get("receipt_mode")
        == "verifier_no_execution_receipt_proof_preview_only"
        and receipt_proof.get("verifier_invocation_locked") is True
        and receipt_proof.get("verifier_invocation_allowed") is False
        and receipt_proof.get("verifier_invoked") is False
        and receipt_proof.get("verifier_receipt_present") is False
        and receipt_proof.get("verifier_receipt_required") is False
        and receipt_proof.get("dry_run_executor_invoked") is False
        and receipt_proof.get("runner_invocation_performed") is False
        and receipt_proof.get("endpoint_executed") is False
        and receipt_proof.get("sql_executed") is False
        and receipt_proof.get("database_written") is False
        and receipt_proof.get("endpoint_execution_allowed") is False
        and receipt_proof.get("sql_execution_allowed") is False
        and receipt_proof.get("database_write_allowed") is False
        and receipt_proof.get("database_apply_authorized") is False
        and receipt_proof.get("executes_database_apply") is False
        and receipt_proof.get("executes_endpoint") is False
        and receipt_proof.get("executes_sql") is False
        and receipt_proof.get("writes_database") is False
        and receipt_proof.get("stdout_included") is False
        and receipt_proof.get("stderr_included") is False
    )
    persistence_guard_bound = (
        receipt_proof_ready
        and bool(persistence_guard_proof.get("guard_proof_id"))
        and persistence_guard_proof.get(
            "source_verifier_no_execution_receipt_proof_closeout_id"
        )
        == closeout_id
        and persistence_guard_proof.get(
            "source_verifier_invocation_lock_proof_closeout_id"
        )
        == source_closeout_id
        and persistence_guard_proof.get(
            "source_verifier_no_execution_receipt_proof_id"
        )
        == source_receipt_id
        and persistence_guard_proof.get("required_command_shape_hash")
        == receipt_proof.get("required_command_shape_hash")
        and int(
            persistence_guard_proof.get(
                "verifier_receipt_persistence_guard_proof_field_count"
            )
            or 0
        )
        == len(persistence_guard_fields)
    )
    persistence_guard_blocks_persistence = (
        persistence_guard_proof.get("guard_mode")
        == "verifier_receipt_persistence_guard_proof_preview_only"
        and persistence_guard_proof.get("verifier_receipt_persistence_locked")
        is True
        and persistence_guard_proof.get("verifier_receipt_persistence_allowed")
        is False
        and persistence_guard_proof.get("verifier_receipt_persisted") is False
        and persistence_guard_proof.get("persists_verifier_receipt") is False
        and persistence_guard_proof.get("persistence_receipt_present") is False
        and persistence_guard_proof.get("verifier_invocation_allowed") is False
        and persistence_guard_proof.get("verifier_invoked") is False
        and persistence_guard_proof.get("dry_run_executor_invoked") is False
        and persistence_guard_proof.get("runner_invocation_performed") is False
        and persistence_guard_proof.get("endpoint_executed") is False
        and persistence_guard_proof.get("sql_executed") is False
        and persistence_guard_proof.get("database_written") is False
        and persistence_guard_proof.get("endpoint_execution_allowed") is False
        and persistence_guard_proof.get("sql_execution_allowed") is False
        and persistence_guard_proof.get("database_write_allowed") is False
        and persistence_guard_proof.get("database_apply_authorized") is False
        and persistence_guard_proof.get("executes_database_apply") is False
        and persistence_guard_proof.get("executes_endpoint") is False
        and persistence_guard_proof.get("executes_sql") is False
        and persistence_guard_proof.get("writes_database") is False
        and persistence_guard_proof.get("stdout_included") is False
        and persistence_guard_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        receipt_closeout.get("verifier_invocation_lock_proof_closeout_only") is True
        and receipt_closeout.get("verifier_no_execution_receipt_proof_only")
        is True
        and previous_lock_closeout.get("frozen_envelope_verifier_handoff_closeout_only")
        is True
        and receipt_proof_no_execute
    )
    target_hash_locked = (
        receipt_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(receipt_closeout.get("expected_sha256"))
        and bool(receipt_closeout.get("actual_sha256"))
        and receipt_closeout.get("expected_sha256")
        == receipt_closeout.get("actual_sha256")
        and receipt_closeout.get("hash_matches") is True
        and receipt_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    contract_blocks_persistence_and_apply = (
        receipt_contract.get(
            "permits_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        )
        is True
        and receipt_contract.get("persists_verifier_receipt") is False
        and receipt_contract.get("executes_database_apply") is False
        and receipt_contract.get("database_apply_authorized") is False
        and receipt_contract.get("writes_database") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("verifier_invoked_count", 0) == 0
        and summary.get("verifier_receipt_present_count", 0) == 0
        and safety.get("persists_verifier_receipt") is False
    )
    checks = [
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "verifier_invocation_lock_proof_closeout_ready",
            receipt_closeout_ready,
            {
                "result": receipt_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count"
                ),
            },
            "wait_for_verifier_invocation_lock_proof_closeout",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "source_closeout_id": source_closeout_id,
                "source_receipt_id": source_receipt_id,
                "lock_proof_id": lock_proof.get("lock_proof_id"),
            },
            "wait_for_source_chain_alignment",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "verifier_no_execution_receipt_proof_ready",
            receipt_proof_ready,
            {
                "receipt_proof_id": source_receipt_id,
                "receipt_status": receipt_proof.get("receipt_status"),
                "field_count": receipt_proof.get(
                    "verifier_no_execution_receipt_proof_field_count"
                ),
            },
            "wait_for_verifier_no_execution_receipt_proof",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "verifier_no_execution_receipt_proof_no_execute",
            receipt_proof_no_execute,
            {
                "receipt_mode": receipt_proof.get("receipt_mode"),
                "verifier_invoked": receipt_proof.get("verifier_invoked"),
                "database_written": receipt_proof.get("database_written"),
            },
            "abort_if_verifier_no_execution_receipt_proof_reports_execution",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "verifier_receipt_persistence_guard_proof_bound",
            persistence_guard_bound,
            {
                "guard_proof_id": persistence_guard_proof.get("guard_proof_id"),
                "source_receipt_id": persistence_guard_proof.get(
                    "source_verifier_no_execution_receipt_proof_id"
                ),
                "field_count": persistence_guard_proof.get(
                    "verifier_receipt_persistence_guard_proof_field_count"
                ),
            },
            "wait_for_verifier_receipt_persistence_guard_proof",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "verifier_receipt_persistence_guard_proof_blocks_persistence",
            persistence_guard_blocks_persistence,
            {
                "guard_mode": persistence_guard_proof.get("guard_mode"),
                "persistence_allowed": persistence_guard_proof.get(
                    "verifier_receipt_persistence_allowed"
                ),
                "persisted": persistence_guard_proof.get(
                    "verifier_receipt_persisted"
                ),
            },
            "abort_if_verifier_receipt_persistence_guard_allows_persistence",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "verifier_invocation_lock_proof_closeout_only": (
                    receipt_closeout.get(
                        "verifier_invocation_lock_proof_closeout_only"
                    )
                ),
                "verifier_no_execution_receipt_proof_only": (
                    receipt_closeout.get("verifier_no_execution_receipt_proof_only")
                ),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": receipt_closeout.get("target_file"),
                "hash_matches": receipt_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    receipt_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(receipt_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "verifier_invocation_lock_proof_closeout_contract_blocks_persistence_and_database_apply",
            contract_blocks_persistence_and_apply,
            {
                "permits_future_no_execution_receipt_proof": receipt_contract.get(
                    "permits_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
                ),
                "persists_verifier_receipt": receipt_contract.get(
                    "persists_verifier_receipt"
                ),
                "database_apply_authorized": receipt_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_persistence_or_database_apply",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "preview_has_no_side_effects_no_persistence_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "verifier_invoked_count": summary.get("verifier_invoked_count", 0),
                "verifier_receipt_present_count": summary.get(
                    "verifier_receipt_present_count", 0
                ),
            },
            "abort_on_preview_persistence_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            receipt_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": receipt_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof = {
        "verifier_no_execution_receipt_proof_closeout_id": closeout_id,
        "verifier_receipt_persistence_guard_proof_id": guard_id,
        "source_verifier_invocation_lock_proof_closeout_id": source_closeout_id,
        "source_verifier_no_execution_receipt_proof_id": source_receipt_id,
        "source_verifier_invocation_lock_proof_id": lock_proof.get("lock_proof_id"),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout": (
            closeout_ready
        ),
        "verifier_no_execution_receipt_proof_closeout_ready": closeout_ready,
        "verifier_invocation_lock_proof_closeout_ready": receipt_closeout_ready,
        "verifier_no_execution_receipt_proof_ready": receipt_proof_ready,
        "verifier_receipt_persistence_guard_proof_bound": closeout_ready,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_verifier_no_execution_receipt_proof_closeout = {
        "verifier_no_execution_receipt_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
        ),
        "source_verifier_invocation_lock_proof_closeout_id": source_closeout_id,
        "source_verifier_no_execution_receipt_proof_id": source_receipt_id,
        "source_verifier_invocation_lock_proof_id": lock_proof.get("lock_proof_id"),
        "required_command_shape_hash": receipt_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof": (
            closeout_ready
        ),
        "verifier_no_execution_receipt_proof_closeout_fields": closeout_fields,
        "verifier_no_execution_receipt_proof_closeout_field_count": len(
            closeout_fields
        ),
        "verifier_no_execution_receipt_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "verifier_no_execution_receipt_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "verifier_receipt_persistence_guard_proof": persistence_guard_proof,
        "verifier_receipt_persistence_guard_proof_count": 1,
        "verifier_receipt_persistence_guard_proof_field_count": len(
            persistence_guard_fields
        ),
        "verifier_no_execution_receipt_proof": receipt_proof,
        "verifier_no_execution_receipt_proof_count": 1,
        "verifier_invocation_lock_proof_closeout": receipt_closeout,
        "verifier_invocation_lock_proof_closeout_count": 1,
        "verifier_invocation_lock_proof": lock_proof,
        "verifier_invocation_lock_proof_count": 1,
        "target_file": receipt_closeout.get("target_file"),
        "expected_sha256": receipt_closeout.get("expected_sha256"),
        "actual_sha256": receipt_closeout.get("actual_sha256"),
        "hash_matches": receipt_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "verifier_no_execution_receipt_proof_closeout_only": True,
        "verifier_receipt_persistence_guard_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract = {
        "mode": "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_and_verifier_receipt_persistence_guard_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-verifier-no-execution-receipt-proof-closeout"
        ),
        "source_verifier_invocation_lock_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-verifier-invocation-lock-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof": (
            closeout_ready
        ),
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_count": 1,
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "verifier_receipt_persistence_guard_proof_count": 1,
            "verifier_receipt_persistence_guard_proof_field_count": len(
                persistence_guard_fields
            ),
            "verifier_receipt_persistence_locked_count": 1,
            "verifier_receipt_persistence_allowed_count": 0,
            "verifier_receipt_persisted_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invocation_locked_count": 1,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(receipt_closeout_result.get("success")),
        "generated_at": receipt_closeout_result.get("generated_at"),
        "source_policy": receipt_closeout_result.get("policy"),
        "stats": receipt_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof": (
            future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof
        ),
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout": (
            controlled_dry_run_verifier_no_execution_receipt_proof_closeout
        ),
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract": (
            controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract
        ),
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_verifier_invocation_lock_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_verifier_invocation_lock_proof_closeout_contract": (
            receipt_contract
        ),
        "source_controlled_dry_run_verifier_invocation_lock_proof_closeout": (
            receipt_closeout
        ),
        "source_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof": (
            future_receipt
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future verifier receipt persistence guard proof closeout.",
            "Keep verifier receipt persistence disabled until a later persistence guard closeout proves the storage boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, verifier invocation, verifier receipt persistence, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the persistence guard proof and prove storage remains locked."""
    storage_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_guard = (
        storage_closeout_result.get(
            "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        )
        or {}
    )
    guard_closeout = (
        storage_closeout_result.get(
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
        )
        or {}
    )
    guard_contract = (
        storage_closeout_result.get(
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract"
        )
        or {}
    )
    summary = storage_closeout_result.get("summary") or {}
    safety = storage_closeout_result.get("safety") or {}
    guard_proof = guard_closeout.get("verifier_receipt_persistence_guard_proof") or {}
    receipt_proof = guard_closeout.get("verifier_no_execution_receipt_proof") or {}
    previous_receipt_closeout = (
        guard_closeout.get("verifier_invocation_lock_proof_closeout") or {}
    )
    rollback_binding = guard_closeout.get("rollback_binding") or {}
    verifier_binding = guard_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = guard_closeout.get(
        "verifier_no_execution_receipt_proof_closeout_id"
    )
    source_guard_id = guard_proof.get("guard_proof_id")
    source_receipt_id = guard_proof.get("source_verifier_no_execution_receipt_proof_id")
    closeout_id = (
        _db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_id(
            storage_closeout_result
        )
    )
    storage_boundary_id = f"{closeout_id}-receipt-persistence-storage-boundary-proof"
    closeout_fields = [
        "verifier_receipt_persistence_guard_proof_closeout_id",
        "source_verifier_no_execution_receipt_proof_closeout_id",
        "source_verifier_receipt_persistence_guard_proof_id",
        "source_verifier_no_execution_receipt_proof_id",
        "receipt_persistence_storage_boundary_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "receipt_persistence_storage_boundary_locked",
        "receipt_persistence_storage_written",
        "abort_conditions",
    ]
    acceptance_gates = [
        "verifier_no_execution_receipt_proof_closeout_ready",
        "source_chain_ids_match",
        "verifier_receipt_persistence_guard_proof_ready",
        "verifier_receipt_persistence_guard_proof_no_persistence",
        "receipt_persistence_storage_boundary_proof_bound",
        "receipt_persistence_storage_boundary_proof_blocks_storage",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_storage_persistence_or_database_apply",
    ]
    storage_boundary_fields = [
        "storage_boundary_proof_id",
        "source_verifier_receipt_persistence_guard_proof_closeout_id",
        "source_verifier_no_execution_receipt_proof_closeout_id",
        "source_verifier_receipt_persistence_guard_proof_id",
        "source_verifier_no_execution_receipt_proof_id",
        "storage_boundary_mode",
        "receipt_persistence_storage_boundary_locked",
        "receipt_persistence_storage_write_allowed",
        "receipt_persistence_storage_written",
        "verifier_receipt_persistence_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_verifier_no_execution_receipt_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_verifier_receipt_persistence_guard_proof_missing",
        "abort_if_verifier_receipt_persistence_guard_allows_persistence",
        "abort_if_receipt_persistence_storage_boundary_missing",
        "abort_if_receipt_persistence_storage_write_is_allowed",
        "abort_if_receipt_persistence_storage_written",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_storage_persistence_or_apply_material_is_present",
    ]
    storage_boundary_proof = {
        "storage_boundary_proof_id": storage_boundary_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": closeout_id,
        "source_verifier_no_execution_receipt_proof_closeout_id": source_closeout_id,
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "source_verifier_no_execution_receipt_proof_id": source_receipt_id,
        "source_verifier_invocation_lock_proof_closeout_id": (
            guard_proof.get("source_verifier_invocation_lock_proof_closeout_id")
        ),
        "source_verifier_invocation_lock_proof_id": (
            guard_proof.get("source_verifier_invocation_lock_proof_id")
        ),
        "required_command_shape_hash": guard_proof.get(
            "required_command_shape_hash"
        ),
        "storage_boundary_status": "receipt_persistence_storage_boundary_proof_preview_ready",
        "storage_boundary_mode": "receipt_persistence_storage_boundary_proof_preview_only",
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "receipt_persistence_storage_receipt_present": False,
        "receipt_persistence_storage_receipt_required": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "receipt_persistence_storage_boundary_proof_field_count": len(
            storage_boundary_fields
        ),
        "receipt_persistence_storage_boundary_proof_fields": (
            storage_boundary_fields
        ),
    }
    guard_closeout_ready = (
        storage_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_guard.get("verifier_no_execution_receipt_proof_closeout_id")
        == guard_proof.get("source_verifier_no_execution_receipt_proof_closeout_id")
        == storage_boundary_proof.get(
            "source_verifier_no_execution_receipt_proof_closeout_id"
        )
        and source_guard_id
        == future_guard.get("verifier_receipt_persistence_guard_proof_id")
        == storage_boundary_proof.get(
            "source_verifier_receipt_persistence_guard_proof_id"
        )
        and source_receipt_id
        == guard_proof.get("source_verifier_no_execution_receipt_proof_id")
        == receipt_proof.get("receipt_proof_id")
        == storage_boundary_proof.get(
            "source_verifier_no_execution_receipt_proof_id"
        )
        and guard_proof.get("required_command_shape_hash")
        == receipt_proof.get("required_command_shape_hash")
        == storage_boundary_proof.get("required_command_shape_hash")
    )
    guard_proof_ready = (
        guard_closeout_ready
        and guard_proof.get("guard_status")
        == "verifier_receipt_persistence_guard_proof_preview_ready"
        and guard_proof.get("guard_proof_id")
        == future_guard.get("verifier_receipt_persistence_guard_proof_id")
        and int(
            guard_proof.get(
                "verifier_receipt_persistence_guard_proof_field_count"
            )
            or 0
        )
        == 12
        and summary.get("verifier_receipt_persistence_guard_proof_count") == 1
    )
    guard_proof_no_persistence = (
        guard_proof.get("guard_mode")
        == "verifier_receipt_persistence_guard_proof_preview_only"
        and guard_proof.get("verifier_receipt_persistence_locked") is True
        and guard_proof.get("verifier_receipt_persistence_allowed") is False
        and guard_proof.get("verifier_receipt_persisted") is False
        and guard_proof.get("persists_verifier_receipt") is False
        and guard_proof.get("persistence_receipt_present") is False
        and guard_proof.get("verifier_invocation_allowed") is False
        and guard_proof.get("verifier_invoked") is False
        and guard_proof.get("dry_run_executor_invoked") is False
        and guard_proof.get("runner_invocation_performed") is False
        and guard_proof.get("endpoint_executed") is False
        and guard_proof.get("sql_executed") is False
        and guard_proof.get("database_written") is False
        and guard_proof.get("endpoint_execution_allowed") is False
        and guard_proof.get("sql_execution_allowed") is False
        and guard_proof.get("database_write_allowed") is False
        and guard_proof.get("database_apply_authorized") is False
        and guard_proof.get("executes_database_apply") is False
        and guard_proof.get("executes_endpoint") is False
        and guard_proof.get("executes_sql") is False
        and guard_proof.get("writes_database") is False
        and guard_proof.get("stdout_included") is False
        and guard_proof.get("stderr_included") is False
    )
    storage_boundary_bound = (
        guard_proof_ready
        and bool(storage_boundary_proof.get("storage_boundary_proof_id"))
        and storage_boundary_proof.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        == closeout_id
        and storage_boundary_proof.get(
            "source_verifier_no_execution_receipt_proof_closeout_id"
        )
        == source_closeout_id
        and storage_boundary_proof.get(
            "source_verifier_receipt_persistence_guard_proof_id"
        )
        == source_guard_id
        and storage_boundary_proof.get("required_command_shape_hash")
        == guard_proof.get("required_command_shape_hash")
        and int(
            storage_boundary_proof.get(
                "receipt_persistence_storage_boundary_proof_field_count"
            )
            or 0
        )
        == len(storage_boundary_fields)
    )
    storage_boundary_blocks_storage = (
        storage_boundary_proof.get("storage_boundary_mode")
        == "receipt_persistence_storage_boundary_proof_preview_only"
        and storage_boundary_proof.get("receipt_persistence_storage_boundary_locked")
        is True
        and storage_boundary_proof.get("receipt_persistence_storage_write_allowed")
        is False
        and storage_boundary_proof.get("receipt_persistence_storage_written")
        is False
        and storage_boundary_proof.get("verifier_receipt_persistence_allowed")
        is False
        and storage_boundary_proof.get("verifier_receipt_persisted") is False
        and storage_boundary_proof.get("persists_verifier_receipt") is False
        and storage_boundary_proof.get("verifier_invoked") is False
        and storage_boundary_proof.get("dry_run_executor_invoked") is False
        and storage_boundary_proof.get("runner_invocation_performed") is False
        and storage_boundary_proof.get("endpoint_executed") is False
        and storage_boundary_proof.get("sql_executed") is False
        and storage_boundary_proof.get("database_written") is False
        and storage_boundary_proof.get("endpoint_execution_allowed") is False
        and storage_boundary_proof.get("sql_execution_allowed") is False
        and storage_boundary_proof.get("database_write_allowed") is False
        and storage_boundary_proof.get("database_apply_authorized") is False
        and storage_boundary_proof.get("executes_database_apply") is False
        and storage_boundary_proof.get("executes_endpoint") is False
        and storage_boundary_proof.get("executes_sql") is False
        and storage_boundary_proof.get("writes_database") is False
        and storage_boundary_proof.get("stdout_included") is False
        and storage_boundary_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        guard_closeout.get("verifier_no_execution_receipt_proof_closeout_only")
        is True
        and guard_closeout.get("verifier_receipt_persistence_guard_proof_only")
        is True
        and previous_receipt_closeout.get(
            "verifier_invocation_lock_proof_closeout_only"
        )
        is True
        and guard_proof_no_persistence
    )
    target_hash_locked = (
        guard_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(guard_closeout.get("expected_sha256"))
        and bool(guard_closeout.get("actual_sha256"))
        and guard_closeout.get("expected_sha256")
        == guard_closeout.get("actual_sha256")
        and guard_closeout.get("hash_matches") is True
        and guard_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    contract_blocks_storage_persistence_and_apply = (
        guard_contract.get(
            "permits_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        )
        is True
        and guard_contract.get("persists_verifier_receipt") is False
        and guard_contract.get("executes_database_apply") is False
        and guard_contract.get("database_apply_authorized") is False
        and guard_contract.get("writes_database") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("persists_verifier_receipt_count", 0) == 0
        and summary.get("verifier_receipt_persisted_count", 0) == 0
        and safety.get("persists_verifier_receipt") is False
    )
    checks = [
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "verifier_no_execution_receipt_proof_closeout_ready",
            guard_closeout_ready,
            {
                "result": storage_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count"
                ),
            },
            "wait_for_verifier_no_execution_receipt_proof_closeout",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "source_closeout_id": source_closeout_id,
                "source_guard_id": source_guard_id,
                "source_receipt_id": source_receipt_id,
            },
            "wait_for_source_chain_alignment",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "verifier_receipt_persistence_guard_proof_ready",
            guard_proof_ready,
            {
                "guard_proof_id": source_guard_id,
                "guard_status": guard_proof.get("guard_status"),
                "field_count": guard_proof.get(
                    "verifier_receipt_persistence_guard_proof_field_count"
                ),
            },
            "wait_for_verifier_receipt_persistence_guard_proof",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "verifier_receipt_persistence_guard_proof_no_persistence",
            guard_proof_no_persistence,
            {
                "guard_mode": guard_proof.get("guard_mode"),
                "persistence_allowed": guard_proof.get(
                    "verifier_receipt_persistence_allowed"
                ),
                "persisted": guard_proof.get("verifier_receipt_persisted"),
            },
            "abort_if_verifier_receipt_persistence_guard_reports_persistence",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "receipt_persistence_storage_boundary_proof_bound",
            storage_boundary_bound,
            {
                "storage_boundary_proof_id": storage_boundary_proof.get(
                    "storage_boundary_proof_id"
                ),
                "source_guard_id": storage_boundary_proof.get(
                    "source_verifier_receipt_persistence_guard_proof_id"
                ),
                "field_count": storage_boundary_proof.get(
                    "receipt_persistence_storage_boundary_proof_field_count"
                ),
            },
            "wait_for_receipt_persistence_storage_boundary_proof",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "receipt_persistence_storage_boundary_proof_blocks_storage",
            storage_boundary_blocks_storage,
            {
                "storage_boundary_mode": storage_boundary_proof.get(
                    "storage_boundary_mode"
                ),
                "storage_write_allowed": storage_boundary_proof.get(
                    "receipt_persistence_storage_write_allowed"
                ),
                "storage_written": storage_boundary_proof.get(
                    "receipt_persistence_storage_written"
                ),
            },
            "abort_if_receipt_persistence_storage_boundary_allows_storage",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "verifier_no_execution_receipt_proof_closeout_only": (
                    guard_closeout.get(
                        "verifier_no_execution_receipt_proof_closeout_only"
                    )
                ),
                "verifier_receipt_persistence_guard_proof_only": (
                    guard_closeout.get(
                        "verifier_receipt_persistence_guard_proof_only"
                    )
                ),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": guard_closeout.get("target_file"),
                "hash_matches": guard_closeout.get("hash_matches"),
                "expected_sha256_present": bool(guard_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(guard_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "verifier_no_execution_receipt_proof_closeout_contract_blocks_storage_persistence_and_database_apply",
            contract_blocks_storage_persistence_and_apply,
            {
                "permits_future_guard_proof": guard_contract.get(
                    "permits_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
                ),
                "persists_verifier_receipt": guard_contract.get(
                    "persists_verifier_receipt"
                ),
                "database_apply_authorized": guard_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_storage_persistence_or_database_apply",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "preview_has_no_side_effects_no_storage_no_persistence_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "persists_verifier_receipt_count": summary.get(
                    "persists_verifier_receipt_count", 0
                ),
            },
            "abort_on_preview_storage_persistence_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            guard_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": guard_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof = {
        "verifier_receipt_persistence_guard_proof_closeout_id": closeout_id,
        "receipt_persistence_storage_boundary_proof_id": storage_boundary_id,
        "source_verifier_no_execution_receipt_proof_closeout_id": source_closeout_id,
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "source_verifier_no_execution_receipt_proof_id": source_receipt_id,
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout": (
            closeout_ready
        ),
        "verifier_receipt_persistence_guard_proof_closeout_ready": closeout_ready,
        "verifier_no_execution_receipt_proof_closeout_ready": guard_closeout_ready,
        "verifier_receipt_persistence_guard_proof_ready": guard_proof_ready,
        "receipt_persistence_storage_boundary_proof_bound": closeout_ready,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout = {
        "verifier_receipt_persistence_guard_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
        ),
        "source_verifier_no_execution_receipt_proof_closeout_id": source_closeout_id,
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "source_verifier_no_execution_receipt_proof_id": source_receipt_id,
        "required_command_shape_hash": guard_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof": (
            closeout_ready
        ),
        "verifier_receipt_persistence_guard_proof_closeout_fields": closeout_fields,
        "verifier_receipt_persistence_guard_proof_closeout_field_count": len(
            closeout_fields
        ),
        "verifier_receipt_persistence_guard_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "verifier_receipt_persistence_guard_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "receipt_persistence_storage_boundary_proof": storage_boundary_proof,
        "receipt_persistence_storage_boundary_proof_count": 1,
        "receipt_persistence_storage_boundary_proof_field_count": len(
            storage_boundary_fields
        ),
        "verifier_receipt_persistence_guard_proof": guard_proof,
        "verifier_receipt_persistence_guard_proof_count": 1,
        "verifier_no_execution_receipt_proof_closeout": guard_closeout,
        "verifier_no_execution_receipt_proof_closeout_count": 1,
        "verifier_no_execution_receipt_proof": receipt_proof,
        "verifier_no_execution_receipt_proof_count": 1,
        "target_file": guard_closeout.get("target_file"),
        "expected_sha256": guard_closeout.get("expected_sha256"),
        "actual_sha256": guard_closeout.get("actual_sha256"),
        "hash_matches": guard_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "verifier_receipt_persistence_guard_proof_closeout_only": True,
        "receipt_persistence_storage_boundary_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract = {
        "mode": "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_and_receipt_persistence_storage_boundary_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-verifier-receipt-persistence-guard-proof-closeout"
        ),
        "source_verifier_no_execution_receipt_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-verifier-no-execution-receipt-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof": (
            closeout_ready
        ),
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_count": 1,
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "receipt_persistence_storage_boundary_proof_count": 1,
            "receipt_persistence_storage_boundary_proof_field_count": len(
                storage_boundary_fields
            ),
            "receipt_persistence_storage_boundary_locked_count": 1,
            "receipt_persistence_storage_write_allowed_count": 0,
            "receipt_persistence_storage_written_count": 0,
            "verifier_receipt_persistence_allowed_count": 0,
            "verifier_receipt_persisted_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(storage_closeout_result.get("success")),
        "generated_at": storage_closeout_result.get("generated_at"),
        "source_policy": storage_closeout_result.get("policy"),
        "stats": storage_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof": (
            future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof
        ),
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout": (
            controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout
        ),
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract": (
            controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract
        ),
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract": (
            guard_contract
        ),
        "source_controlled_dry_run_verifier_no_execution_receipt_proof_closeout": (
            guard_closeout
        ),
        "source_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof": (
            future_guard
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future receipt persistence storage boundary proof closeout.",
            "Keep receipt persistence storage disabled until a later storage boundary closeout proves the write boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, verifier invocation, verifier receipt persistence, receipt storage, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the storage boundary proof and add a no-write ledger proof."""
    ledger_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_storage = (
        ledger_closeout_result.get(
            "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        )
        or {}
    )
    storage_closeout = (
        ledger_closeout_result.get(
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
        )
        or {}
    )
    storage_contract = (
        ledger_closeout_result.get(
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract"
        )
        or {}
    )
    summary = ledger_closeout_result.get("summary") or {}
    safety = ledger_closeout_result.get("safety") or {}
    storage_proof = (
        storage_closeout.get("receipt_persistence_storage_boundary_proof") or {}
    )
    guard_proof = (
        storage_closeout.get("verifier_receipt_persistence_guard_proof") or {}
    )
    previous_guard_closeout = (
        storage_closeout.get("verifier_no_execution_receipt_proof_closeout") or {}
    )
    rollback_binding = storage_closeout.get("rollback_binding") or {}
    verifier_binding = storage_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = storage_closeout.get(
        "verifier_receipt_persistence_guard_proof_closeout_id"
    )
    source_storage_id = storage_proof.get("storage_boundary_proof_id")
    source_guard_id = storage_proof.get(
        "source_verifier_receipt_persistence_guard_proof_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_id(
            ledger_closeout_result
        )
    )
    ledger_id = f"{closeout_id}-storage-boundary-no-write-ledger-proof"
    closeout_fields = [
        "receipt_persistence_storage_boundary_proof_closeout_id",
        "source_verifier_receipt_persistence_guard_proof_closeout_id",
        "source_receipt_persistence_storage_boundary_proof_id",
        "source_verifier_receipt_persistence_guard_proof_id",
        "storage_boundary_no_write_ledger_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "storage_boundary_write_locked",
        "storage_boundary_written",
        "abort_conditions",
    ]
    acceptance_gates = [
        "verifier_receipt_persistence_guard_proof_closeout_ready",
        "source_chain_ids_match",
        "receipt_persistence_storage_boundary_proof_ready",
        "receipt_persistence_storage_boundary_proof_no_write",
        "storage_boundary_no_write_ledger_proof_bound",
        "storage_boundary_no_write_ledger_proof_blocks_write",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_ledger_storage_persistence_or_database_apply",
    ]
    no_write_ledger_fields = [
        "ledger_proof_id",
        "source_receipt_persistence_storage_boundary_proof_closeout_id",
        "source_verifier_receipt_persistence_guard_proof_closeout_id",
        "source_receipt_persistence_storage_boundary_proof_id",
        "source_verifier_receipt_persistence_guard_proof_id",
        "ledger_mode",
        "storage_boundary_write_locked",
        "storage_boundary_write_allowed",
        "storage_boundary_written",
        "ledger_write_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_verifier_receipt_persistence_guard_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_receipt_persistence_storage_boundary_proof_missing",
        "abort_if_receipt_persistence_storage_boundary_allows_write",
        "abort_if_storage_boundary_no_write_ledger_missing",
        "abort_if_storage_boundary_no_write_ledger_allows_write",
        "abort_if_storage_boundary_or_ledger_written",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_ledger_storage_persistence_or_apply_material_is_present",
    ]
    no_write_ledger_proof = {
        "ledger_proof_id": ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": closeout_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "source_verifier_no_execution_receipt_proof_closeout_id": (
            storage_proof.get("source_verifier_no_execution_receipt_proof_closeout_id")
        ),
        "source_verifier_no_execution_receipt_proof_id": (
            storage_proof.get("source_verifier_no_execution_receipt_proof_id")
        ),
        "required_command_shape_hash": storage_proof.get(
            "required_command_shape_hash"
        ),
        "ledger_status": "storage_boundary_no_write_ledger_proof_preview_ready",
        "ledger_mode": "storage_boundary_no_write_ledger_proof_preview_only",
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "ledger_receipt_present": False,
        "ledger_receipt_required": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "storage_boundary_no_write_ledger_proof_field_count": len(
            no_write_ledger_fields
        ),
        "storage_boundary_no_write_ledger_proof_fields": no_write_ledger_fields,
    }
    storage_closeout_ready = (
        ledger_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_storage.get("verifier_receipt_persistence_guard_proof_closeout_id")
        == storage_proof.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        == no_write_ledger_proof.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        and source_storage_id
        == future_storage.get("receipt_persistence_storage_boundary_proof_id")
        == no_write_ledger_proof.get(
            "source_receipt_persistence_storage_boundary_proof_id"
        )
        and source_guard_id
        == storage_proof.get("source_verifier_receipt_persistence_guard_proof_id")
        == guard_proof.get("guard_proof_id")
        == no_write_ledger_proof.get(
            "source_verifier_receipt_persistence_guard_proof_id"
        )
        and storage_proof.get("required_command_shape_hash")
        == guard_proof.get("required_command_shape_hash")
        == no_write_ledger_proof.get("required_command_shape_hash")
    )
    storage_boundary_proof_ready = (
        storage_closeout_ready
        and storage_proof.get("storage_boundary_status")
        == "receipt_persistence_storage_boundary_proof_preview_ready"
        and storage_proof.get("storage_boundary_proof_id")
        == future_storage.get("receipt_persistence_storage_boundary_proof_id")
        and int(
            storage_proof.get(
                "receipt_persistence_storage_boundary_proof_field_count"
            )
            or 0
        )
        == 12
        and summary.get("receipt_persistence_storage_boundary_proof_count") == 1
    )
    storage_boundary_proof_no_write = (
        storage_proof.get("storage_boundary_mode")
        == "receipt_persistence_storage_boundary_proof_preview_only"
        and storage_proof.get("receipt_persistence_storage_boundary_locked")
        is True
        and storage_proof.get("receipt_persistence_storage_write_allowed") is False
        and storage_proof.get("receipt_persistence_storage_written") is False
        and storage_proof.get("verifier_receipt_persistence_allowed") is False
        and storage_proof.get("verifier_receipt_persisted") is False
        and storage_proof.get("persists_verifier_receipt") is False
        and storage_proof.get("verifier_invoked") is False
        and storage_proof.get("dry_run_executor_invoked") is False
        and storage_proof.get("runner_invocation_performed") is False
        and storage_proof.get("endpoint_executed") is False
        and storage_proof.get("sql_executed") is False
        and storage_proof.get("database_written") is False
        and storage_proof.get("endpoint_execution_allowed") is False
        and storage_proof.get("sql_execution_allowed") is False
        and storage_proof.get("database_write_allowed") is False
        and storage_proof.get("database_apply_authorized") is False
        and storage_proof.get("executes_database_apply") is False
        and storage_proof.get("executes_endpoint") is False
        and storage_proof.get("executes_sql") is False
        and storage_proof.get("writes_database") is False
        and storage_proof.get("stdout_included") is False
        and storage_proof.get("stderr_included") is False
    )
    no_write_ledger_bound = (
        storage_boundary_proof_ready
        and bool(no_write_ledger_proof.get("ledger_proof_id"))
        and no_write_ledger_proof.get(
            "source_receipt_persistence_storage_boundary_proof_closeout_id"
        )
        == closeout_id
        and no_write_ledger_proof.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        == source_closeout_id
        and no_write_ledger_proof.get(
            "source_receipt_persistence_storage_boundary_proof_id"
        )
        == source_storage_id
        and no_write_ledger_proof.get("required_command_shape_hash")
        == storage_proof.get("required_command_shape_hash")
        and int(
            no_write_ledger_proof.get(
                "storage_boundary_no_write_ledger_proof_field_count"
            )
            or 0
        )
        == len(no_write_ledger_fields)
    )
    no_write_ledger_blocks_write = (
        no_write_ledger_proof.get("ledger_mode")
        == "storage_boundary_no_write_ledger_proof_preview_only"
        and no_write_ledger_proof.get("storage_boundary_write_locked") is True
        and no_write_ledger_proof.get("storage_boundary_write_allowed") is False
        and no_write_ledger_proof.get("storage_boundary_written") is False
        and no_write_ledger_proof.get("ledger_write_allowed") is False
        and no_write_ledger_proof.get("ledger_written") is False
        and no_write_ledger_proof.get("receipt_persistence_storage_write_allowed")
        is False
        and no_write_ledger_proof.get("receipt_persistence_storage_written")
        is False
        and no_write_ledger_proof.get("verifier_receipt_persistence_allowed")
        is False
        and no_write_ledger_proof.get("verifier_receipt_persisted") is False
        and no_write_ledger_proof.get("persists_verifier_receipt") is False
        and no_write_ledger_proof.get("verifier_invoked") is False
        and no_write_ledger_proof.get("dry_run_executor_invoked") is False
        and no_write_ledger_proof.get("runner_invocation_performed") is False
        and no_write_ledger_proof.get("endpoint_executed") is False
        and no_write_ledger_proof.get("sql_executed") is False
        and no_write_ledger_proof.get("database_written") is False
        and no_write_ledger_proof.get("endpoint_execution_allowed") is False
        and no_write_ledger_proof.get("sql_execution_allowed") is False
        and no_write_ledger_proof.get("database_write_allowed") is False
        and no_write_ledger_proof.get("database_apply_authorized") is False
        and no_write_ledger_proof.get("executes_database_apply") is False
        and no_write_ledger_proof.get("executes_endpoint") is False
        and no_write_ledger_proof.get("executes_sql") is False
        and no_write_ledger_proof.get("writes_database") is False
        and no_write_ledger_proof.get("stdout_included") is False
        and no_write_ledger_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        storage_closeout.get("verifier_receipt_persistence_guard_proof_closeout_only")
        is True
        and storage_closeout.get("receipt_persistence_storage_boundary_proof_only")
        is True
        and previous_guard_closeout.get(
            "verifier_no_execution_receipt_proof_closeout_only"
        )
        is True
        and storage_boundary_proof_no_write
    )
    target_hash_locked = (
        storage_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(storage_closeout.get("expected_sha256"))
        and bool(storage_closeout.get("actual_sha256"))
        and storage_closeout.get("expected_sha256")
        == storage_closeout.get("actual_sha256")
        and storage_closeout.get("hash_matches") is True
        and storage_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    contract_blocks_ledger_storage_persistence_and_apply = (
        storage_contract.get(
            "permits_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        )
        is True
        and storage_contract.get("receipt_persistence_storage_write_allowed")
        is False
        and storage_contract.get("receipt_persistence_storage_written") is False
        and storage_contract.get("persists_verifier_receipt") is False
        and storage_contract.get("executes_database_apply") is False
        and storage_contract.get("database_apply_authorized") is False
        and storage_contract.get("writes_database") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("receipt_persistence_storage_write_allowed_count", 0) == 0
        and summary.get("receipt_persistence_storage_written_count", 0) == 0
        and summary.get("persists_verifier_receipt_count", 0) == 0
        and safety.get("persists_verifier_receipt") is False
    )
    checks = [
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "verifier_receipt_persistence_guard_proof_closeout_ready",
            storage_closeout_ready,
            {
                "result": ledger_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count"
                ),
            },
            "wait_for_verifier_receipt_persistence_guard_proof_closeout",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "source_closeout_id": source_closeout_id,
                "source_storage_id": source_storage_id,
                "source_guard_id": source_guard_id,
            },
            "wait_for_source_chain_alignment",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "receipt_persistence_storage_boundary_proof_ready",
            storage_boundary_proof_ready,
            {
                "storage_boundary_proof_id": source_storage_id,
                "storage_boundary_status": storage_proof.get(
                    "storage_boundary_status"
                ),
                "field_count": storage_proof.get(
                    "receipt_persistence_storage_boundary_proof_field_count"
                ),
            },
            "wait_for_receipt_persistence_storage_boundary_proof",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "receipt_persistence_storage_boundary_proof_no_write",
            storage_boundary_proof_no_write,
            {
                "storage_boundary_mode": storage_proof.get(
                    "storage_boundary_mode"
                ),
                "storage_write_allowed": storage_proof.get(
                    "receipt_persistence_storage_write_allowed"
                ),
                "storage_written": storage_proof.get(
                    "receipt_persistence_storage_written"
                ),
            },
            "abort_if_receipt_persistence_storage_boundary_reports_write",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "storage_boundary_no_write_ledger_proof_bound",
            no_write_ledger_bound,
            {
                "ledger_proof_id": no_write_ledger_proof.get("ledger_proof_id"),
                "source_storage_id": no_write_ledger_proof.get(
                    "source_receipt_persistence_storage_boundary_proof_id"
                ),
                "field_count": no_write_ledger_proof.get(
                    "storage_boundary_no_write_ledger_proof_field_count"
                ),
            },
            "wait_for_storage_boundary_no_write_ledger_proof",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "storage_boundary_no_write_ledger_proof_blocks_write",
            no_write_ledger_blocks_write,
            {
                "ledger_mode": no_write_ledger_proof.get("ledger_mode"),
                "ledger_write_allowed": no_write_ledger_proof.get(
                    "ledger_write_allowed"
                ),
                "ledger_written": no_write_ledger_proof.get("ledger_written"),
            },
            "abort_if_storage_boundary_no_write_ledger_allows_write",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "verifier_receipt_persistence_guard_proof_closeout_only": (
                    storage_closeout.get(
                        "verifier_receipt_persistence_guard_proof_closeout_only"
                    )
                ),
                "receipt_persistence_storage_boundary_proof_only": (
                    storage_closeout.get(
                        "receipt_persistence_storage_boundary_proof_only"
                    )
                ),
            },
            "wait_for_previous_closeouts_carry_forward",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": storage_closeout.get("target_file"),
                "hash_matches": storage_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    storage_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(storage_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "verifier_receipt_persistence_guard_proof_closeout_contract_blocks_ledger_storage_persistence_and_database_apply",
            contract_blocks_ledger_storage_persistence_and_apply,
            {
                "permits_future_storage_boundary_proof": storage_contract.get(
                    "permits_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
                ),
                "receipt_persistence_storage_write_allowed": storage_contract.get(
                    "receipt_persistence_storage_write_allowed"
                ),
                "database_apply_authorized": storage_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_ledger_storage_persistence_or_database_apply",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "preview_has_no_side_effects_no_ledger_no_storage_no_persistence_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "receipt_persistence_storage_written_count": summary.get(
                    "receipt_persistence_storage_written_count", 0
                ),
            },
            "abort_on_preview_ledger_storage_persistence_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            storage_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": storage_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof = {
        "receipt_persistence_storage_boundary_proof_closeout_id": closeout_id,
        "storage_boundary_no_write_ledger_proof_id": ledger_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout": (
            closeout_ready
        ),
        "receipt_persistence_storage_boundary_proof_closeout_ready": closeout_ready,
        "verifier_receipt_persistence_guard_proof_closeout_ready": (
            storage_closeout_ready
        ),
        "receipt_persistence_storage_boundary_proof_ready": (
            storage_boundary_proof_ready
        ),
        "storage_boundary_no_write_ledger_proof_bound": closeout_ready,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout = {
        "receipt_persistence_storage_boundary_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
        ),
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": storage_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof": (
            closeout_ready
        ),
        "receipt_persistence_storage_boundary_proof_closeout_fields": (
            closeout_fields
        ),
        "receipt_persistence_storage_boundary_proof_closeout_field_count": len(
            closeout_fields
        ),
        "receipt_persistence_storage_boundary_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "receipt_persistence_storage_boundary_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "storage_boundary_no_write_ledger_proof": no_write_ledger_proof,
        "storage_boundary_no_write_ledger_proof_count": 1,
        "storage_boundary_no_write_ledger_proof_field_count": len(
            no_write_ledger_fields
        ),
        "receipt_persistence_storage_boundary_proof": storage_proof,
        "receipt_persistence_storage_boundary_proof_count": 1,
        "verifier_receipt_persistence_guard_proof_closeout": storage_closeout,
        "verifier_receipt_persistence_guard_proof_closeout_count": 1,
        "verifier_receipt_persistence_guard_proof": guard_proof,
        "verifier_receipt_persistence_guard_proof_count": 1,
        "target_file": storage_closeout.get("target_file"),
        "expected_sha256": storage_closeout.get("expected_sha256"),
        "actual_sha256": storage_closeout.get("actual_sha256"),
        "hash_matches": storage_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "receipt_persistence_storage_boundary_proof_closeout_only": True,
        "storage_boundary_no_write_ledger_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "dry_run_executor_invocation_allowed": False,
        "runner_invocation_allowed": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract = {
        "mode": "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_and_storage_boundary_no_write_ledger_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-receipt-persistence-storage-boundary-proof-closeout"
        ),
        "source_verifier_receipt_persistence_guard_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-verifier-receipt-persistence-guard-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof": (
            closeout_ready
        ),
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_count": 1,
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "storage_boundary_no_write_ledger_proof_count": 1,
            "storage_boundary_no_write_ledger_proof_field_count": len(
                no_write_ledger_fields
            ),
            "storage_boundary_write_locked_count": 1,
            "storage_boundary_write_allowed_count": 0,
            "storage_boundary_written_count": 0,
            "ledger_write_allowed_count": 0,
            "ledger_written_count": 0,
            "receipt_persistence_storage_write_allowed_count": 0,
            "receipt_persistence_storage_written_count": 0,
            "verifier_receipt_persistence_allowed_count": 0,
            "verifier_receipt_persisted_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(ledger_closeout_result.get("success")),
        "generated_at": ledger_closeout_result.get("generated_at"),
        "source_policy": ledger_closeout_result.get("policy"),
        "stats": ledger_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof": (
            future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof
        ),
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout": (
            controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout
        ),
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract": (
            controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract
        ),
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract": (
            storage_contract
        ),
        "source_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout": (
            storage_closeout
        ),
        "source_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof": (
            future_storage
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future storage boundary no-write ledger proof closeout.",
            "Keep storage-boundary ledger writes disabled until a later no-write ledger closeout proves the ledger boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, ledger writes, verifier invocation, verifier receipt persistence, receipt storage, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the no-write ledger proof and add a retention proof."""
    retention_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_ledger = (
        retention_closeout_result.get(
            "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        )
        or {}
    )
    ledger_closeout = (
        retention_closeout_result.get(
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
        )
        or {}
    )
    ledger_contract = (
        retention_closeout_result.get(
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract"
        )
        or {}
    )
    summary = retention_closeout_result.get("summary") or {}
    safety = retention_closeout_result.get("safety") or {}
    no_write_ledger_proof = (
        ledger_closeout.get("storage_boundary_no_write_ledger_proof") or {}
    )
    storage_proof = (
        ledger_closeout.get("receipt_persistence_storage_boundary_proof") or {}
    )
    previous_storage_closeout = (
        ledger_closeout.get("verifier_receipt_persistence_guard_proof_closeout")
        or {}
    )
    rollback_binding = ledger_closeout.get("rollback_binding") or {}
    verifier_binding = ledger_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = ledger_closeout.get(
        "receipt_persistence_storage_boundary_proof_closeout_id"
    )
    source_ledger_id = no_write_ledger_proof.get("ledger_proof_id")
    source_storage_id = no_write_ledger_proof.get(
        "source_receipt_persistence_storage_boundary_proof_id"
    )
    source_guard_closeout_id = no_write_ledger_proof.get(
        "source_verifier_receipt_persistence_guard_proof_closeout_id"
    )
    source_guard_id = no_write_ledger_proof.get(
        "source_verifier_receipt_persistence_guard_proof_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_id(
            retention_closeout_result
        )
    )
    retention_id = f"{closeout_id}-no-write-ledger-retention-proof"
    closeout_fields = [
        "storage_boundary_no_write_ledger_proof_closeout_id",
        "source_receipt_persistence_storage_boundary_proof_closeout_id",
        "source_storage_boundary_no_write_ledger_proof_id",
        "source_receipt_persistence_storage_boundary_proof_id",
        "source_verifier_receipt_persistence_guard_proof_closeout_id",
        "no_write_ledger_retention_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "ledger_retention_write_locked",
        "abort_conditions",
    ]
    acceptance_gates = [
        "receipt_persistence_storage_boundary_proof_closeout_ready",
        "source_chain_ids_match",
        "storage_boundary_no_write_ledger_proof_ready",
        "storage_boundary_no_write_ledger_proof_no_write",
        "no_write_ledger_retention_proof_bound",
        "no_write_ledger_retention_proof_blocks_persistence",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_ledger_storage_retention_persistence_or_database_apply",
    ]
    retention_fields = [
        "retention_proof_id",
        "source_storage_boundary_no_write_ledger_proof_closeout_id",
        "source_storage_boundary_no_write_ledger_proof_id",
        "source_receipt_persistence_storage_boundary_proof_closeout_id",
        "source_receipt_persistence_storage_boundary_proof_id",
        "retention_mode",
        "ledger_retention_write_locked",
        "ledger_retention_write_allowed",
        "ledger_retention_written",
        "ledger_write_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_receipt_persistence_storage_boundary_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_storage_boundary_no_write_ledger_proof_missing",
        "abort_if_storage_boundary_no_write_ledger_allows_write",
        "abort_if_no_write_ledger_retention_proof_missing",
        "abort_if_no_write_ledger_retention_allows_write",
        "abort_if_ledger_or_retention_written",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_ledger_retention_storage_persistence_or_apply_material_is_present",
    ]
    retention_proof = {
        "retention_proof_id": retention_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": closeout_id,
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": no_write_ledger_proof.get(
            "required_command_shape_hash"
        ),
        "retention_status": "no_write_ledger_retention_proof_preview_ready",
        "retention_mode": "no_write_ledger_retention_proof_preview_only",
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "retention_receipt_present": False,
        "retention_receipt_required": False,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "ledger_receipt_present": False,
        "ledger_receipt_required": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "no_write_ledger_retention_proof_field_count": len(retention_fields),
        "no_write_ledger_retention_proof_fields": retention_fields,
    }
    ledger_closeout_ready = (
        retention_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_ledger.get(
            "receipt_persistence_storage_boundary_proof_closeout_id"
        )
        == no_write_ledger_proof.get(
            "source_receipt_persistence_storage_boundary_proof_closeout_id"
        )
        == retention_proof.get(
            "source_receipt_persistence_storage_boundary_proof_closeout_id"
        )
        and source_ledger_id
        == future_ledger.get("storage_boundary_no_write_ledger_proof_id")
        == retention_proof.get("source_storage_boundary_no_write_ledger_proof_id")
        and source_storage_id
        == future_ledger.get("source_receipt_persistence_storage_boundary_proof_id")
        == storage_proof.get("storage_boundary_proof_id")
        == retention_proof.get(
            "source_receipt_persistence_storage_boundary_proof_id"
        )
        and source_guard_closeout_id
        == future_ledger.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        == retention_proof.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        and source_guard_id
        == future_ledger.get("source_verifier_receipt_persistence_guard_proof_id")
        == retention_proof.get("source_verifier_receipt_persistence_guard_proof_id")
        and no_write_ledger_proof.get("required_command_shape_hash")
        == storage_proof.get("required_command_shape_hash")
        == retention_proof.get("required_command_shape_hash")
    )
    no_write_ledger_ready = (
        ledger_closeout_ready
        and no_write_ledger_proof.get("ledger_status")
        == "storage_boundary_no_write_ledger_proof_preview_ready"
        and no_write_ledger_proof.get("ledger_proof_id")
        == future_ledger.get("storage_boundary_no_write_ledger_proof_id")
        and int(
            no_write_ledger_proof.get(
                "storage_boundary_no_write_ledger_proof_field_count"
            )
            or 0
        )
        == 12
        and summary.get("storage_boundary_no_write_ledger_proof_count") == 1
    )
    no_write_ledger_no_write = (
        no_write_ledger_proof.get("ledger_mode")
        == "storage_boundary_no_write_ledger_proof_preview_only"
        and no_write_ledger_proof.get("storage_boundary_write_locked") is True
        and no_write_ledger_proof.get("storage_boundary_write_allowed") is False
        and no_write_ledger_proof.get("storage_boundary_written") is False
        and no_write_ledger_proof.get("ledger_write_allowed") is False
        and no_write_ledger_proof.get("ledger_written") is False
        and no_write_ledger_proof.get("receipt_persistence_storage_write_allowed")
        is False
        and no_write_ledger_proof.get("receipt_persistence_storage_written")
        is False
        and no_write_ledger_proof.get("verifier_receipt_persistence_allowed")
        is False
        and no_write_ledger_proof.get("verifier_receipt_persisted") is False
        and no_write_ledger_proof.get("persists_verifier_receipt") is False
        and no_write_ledger_proof.get("verifier_invoked") is False
        and no_write_ledger_proof.get("dry_run_executor_invoked") is False
        and no_write_ledger_proof.get("runner_invocation_performed") is False
        and no_write_ledger_proof.get("endpoint_executed") is False
        and no_write_ledger_proof.get("sql_executed") is False
        and no_write_ledger_proof.get("database_written") is False
        and no_write_ledger_proof.get("endpoint_execution_allowed") is False
        and no_write_ledger_proof.get("sql_execution_allowed") is False
        and no_write_ledger_proof.get("database_write_allowed") is False
        and no_write_ledger_proof.get("database_apply_authorized") is False
        and no_write_ledger_proof.get("executes_database_apply") is False
        and no_write_ledger_proof.get("executes_endpoint") is False
        and no_write_ledger_proof.get("executes_sql") is False
        and no_write_ledger_proof.get("writes_database") is False
        and no_write_ledger_proof.get("stdout_included") is False
        and no_write_ledger_proof.get("stderr_included") is False
    )
    retention_bound = (
        no_write_ledger_ready
        and bool(retention_proof.get("retention_proof_id"))
        and retention_proof.get(
            "source_storage_boundary_no_write_ledger_proof_closeout_id"
        )
        == closeout_id
        and retention_proof.get("source_storage_boundary_no_write_ledger_proof_id")
        == source_ledger_id
        and retention_proof.get(
            "source_receipt_persistence_storage_boundary_proof_closeout_id"
        )
        == source_closeout_id
        and retention_proof.get("source_receipt_persistence_storage_boundary_proof_id")
        == source_storage_id
        and retention_proof.get("required_command_shape_hash")
        == no_write_ledger_proof.get("required_command_shape_hash")
        and int(
            retention_proof.get("no_write_ledger_retention_proof_field_count")
            or 0
        )
        == len(retention_fields)
    )
    retention_blocks_persistence = (
        retention_proof.get("retention_mode")
        == "no_write_ledger_retention_proof_preview_only"
        and retention_proof.get("ledger_retention_write_locked") is True
        and retention_proof.get("ledger_retention_write_allowed") is False
        and retention_proof.get("ledger_retention_written") is False
        and retention_proof.get("ledger_write_allowed") is False
        and retention_proof.get("ledger_written") is False
        and retention_proof.get("receipt_persistence_storage_write_allowed")
        is False
        and retention_proof.get("receipt_persistence_storage_written") is False
        and retention_proof.get("verifier_receipt_persistence_allowed") is False
        and retention_proof.get("verifier_receipt_persisted") is False
        and retention_proof.get("persists_verifier_receipt") is False
        and retention_proof.get("verifier_invoked") is False
        and retention_proof.get("dry_run_executor_invoked") is False
        and retention_proof.get("runner_invocation_performed") is False
        and retention_proof.get("endpoint_executed") is False
        and retention_proof.get("sql_executed") is False
        and retention_proof.get("database_written") is False
        and retention_proof.get("endpoint_execution_allowed") is False
        and retention_proof.get("sql_execution_allowed") is False
        and retention_proof.get("database_write_allowed") is False
        and retention_proof.get("database_apply_authorized") is False
        and retention_proof.get("executes_database_apply") is False
        and retention_proof.get("executes_endpoint") is False
        and retention_proof.get("executes_sql") is False
        and retention_proof.get("writes_database") is False
        and retention_proof.get("stdout_included") is False
        and retention_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        ledger_closeout.get("receipt_persistence_storage_boundary_proof_closeout_only")
        is True
        and ledger_closeout.get("storage_boundary_no_write_ledger_proof_only")
        is True
        and previous_storage_closeout.get(
            "verifier_receipt_persistence_guard_proof_closeout_only"
        )
        is True
        and no_write_ledger_no_write
    )
    target_hash_locked = (
        ledger_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(ledger_closeout.get("expected_sha256"))
        and bool(ledger_closeout.get("actual_sha256"))
        and ledger_closeout.get("expected_sha256")
        == ledger_closeout.get("actual_sha256")
        and ledger_closeout.get("hash_matches") is True
        and ledger_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    contract_blocks_retention_storage_persistence_and_apply = (
        ledger_contract.get(
            "permits_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        )
        is True
        and ledger_contract.get("storage_boundary_write_allowed") is False
        and ledger_contract.get("storage_boundary_written") is False
        and ledger_contract.get("ledger_write_allowed") is False
        and ledger_contract.get("ledger_written") is False
        and ledger_contract.get("receipt_persistence_storage_write_allowed")
        is False
        and ledger_contract.get("receipt_persistence_storage_written") is False
        and ledger_contract.get("persists_verifier_receipt") is False
        and ledger_contract.get("executes_database_apply") is False
        and ledger_contract.get("database_apply_authorized") is False
        and ledger_contract.get("writes_database") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("ledger_write_allowed_count", 0) == 0
        and summary.get("ledger_written_count", 0) == 0
        and summary.get("receipt_persistence_storage_write_allowed_count", 0) == 0
        and summary.get("receipt_persistence_storage_written_count", 0) == 0
        and summary.get("persists_verifier_receipt_count", 0) == 0
        and safety.get("persists_verifier_receipt") is False
    )
    checks = [
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "receipt_persistence_storage_boundary_proof_closeout_ready",
            ledger_closeout_ready,
            {
                "result": retention_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count"
                ),
            },
            "wait_for_receipt_persistence_storage_boundary_proof_closeout",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "source_closeout_id": source_closeout_id,
                "source_ledger_id": source_ledger_id,
                "source_storage_id": source_storage_id,
                "source_guard_closeout_id": source_guard_closeout_id,
            },
            "wait_for_source_chain_alignment",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "storage_boundary_no_write_ledger_proof_ready",
            no_write_ledger_ready,
            {
                "ledger_proof_id": source_ledger_id,
                "ledger_status": no_write_ledger_proof.get("ledger_status"),
                "field_count": no_write_ledger_proof.get(
                    "storage_boundary_no_write_ledger_proof_field_count"
                ),
            },
            "wait_for_storage_boundary_no_write_ledger_proof",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "storage_boundary_no_write_ledger_proof_no_write",
            no_write_ledger_no_write,
            {
                "ledger_mode": no_write_ledger_proof.get("ledger_mode"),
                "ledger_write_allowed": no_write_ledger_proof.get(
                    "ledger_write_allowed"
                ),
                "database_apply_authorized": no_write_ledger_proof.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_storage_boundary_no_write_ledger_allows_write",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "no_write_ledger_retention_proof_bound",
            retention_bound,
            {
                "retention_proof_id": retention_id,
                "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
                "field_count": retention_proof.get(
                    "no_write_ledger_retention_proof_field_count"
                ),
            },
            "wait_for_no_write_ledger_retention_proof",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "no_write_ledger_retention_proof_blocks_persistence",
            retention_blocks_persistence,
            {
                "retention_mode": retention_proof.get("retention_mode"),
                "ledger_retention_write_allowed": retention_proof.get(
                    "ledger_retention_write_allowed"
                ),
                "ledger_retention_written": retention_proof.get(
                    "ledger_retention_written"
                ),
            },
            "abort_if_no_write_ledger_retention_allows_persistence",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "source_closeout_only": ledger_closeout.get(
                    "receipt_persistence_storage_boundary_proof_closeout_only"
                ),
                "source_ledger_only": ledger_closeout.get(
                    "storage_boundary_no_write_ledger_proof_only"
                ),
            },
            "wait_for_previous_closeouts",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": ledger_closeout.get("target_file"),
                "hash_matches": ledger_closeout.get("hash_matches"),
                "expected_sha256_present": bool(ledger_closeout.get("expected_sha256")),
                "actual_sha256_present": bool(ledger_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "receipt_persistence_storage_boundary_proof_closeout_contract_blocks_retention_storage_persistence_and_database_apply",
            contract_blocks_retention_storage_persistence_and_apply,
            {
                "permits_future_storage_boundary_no_write_ledger_proof": ledger_contract.get(
                    "permits_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
                ),
                "ledger_write_allowed": ledger_contract.get("ledger_write_allowed"),
                "database_apply_authorized": ledger_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_retention_storage_persistence_or_database_apply",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "preview_has_no_side_effects_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "ledger_written_count": summary.get("ledger_written_count", 0),
            },
            "abort_on_preview_retention_ledger_storage_persistence_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            ledger_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": ledger_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_no_write_ledger_retention_proof = {
        "storage_boundary_no_write_ledger_proof_closeout_id": closeout_id,
        "no_write_ledger_retention_proof_id": retention_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_closeout_id
        ),
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout": (
            closeout_ready
        ),
        "storage_boundary_no_write_ledger_proof_closeout_ready": closeout_ready,
        "receipt_persistence_storage_boundary_proof_closeout_ready": (
            ledger_closeout_ready
        ),
        "storage_boundary_no_write_ledger_proof_ready": no_write_ledger_ready,
        "no_write_ledger_retention_proof_bound": closeout_ready,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout = {
        "storage_boundary_no_write_ledger_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
        ),
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_closeout_id
        ),
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": no_write_ledger_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof": (
            closeout_ready
        ),
        "storage_boundary_no_write_ledger_proof_closeout_fields": closeout_fields,
        "storage_boundary_no_write_ledger_proof_closeout_field_count": len(
            closeout_fields
        ),
        "storage_boundary_no_write_ledger_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "storage_boundary_no_write_ledger_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "no_write_ledger_retention_proof": retention_proof,
        "no_write_ledger_retention_proof_count": 1,
        "no_write_ledger_retention_proof_field_count": len(retention_fields),
        "storage_boundary_no_write_ledger_proof": no_write_ledger_proof,
        "storage_boundary_no_write_ledger_proof_count": 1,
        "receipt_persistence_storage_boundary_proof_closeout": ledger_closeout,
        "receipt_persistence_storage_boundary_proof_closeout_count": 1,
        "receipt_persistence_storage_boundary_proof": storage_proof,
        "receipt_persistence_storage_boundary_proof_count": 1,
        "target_file": ledger_closeout.get("target_file"),
        "expected_sha256": ledger_closeout.get("expected_sha256"),
        "actual_sha256": ledger_closeout.get("actual_sha256"),
        "hash_matches": ledger_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "storage_boundary_no_write_ledger_proof_closeout_only": True,
        "no_write_ledger_retention_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract = {
        "mode": "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_and_no_write_ledger_retention_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-storage-boundary-no-write-ledger-proof-closeout"
        ),
        "source_receipt_persistence_storage_boundary_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-receipt-persistence-storage-boundary-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof": (
            closeout_ready
        ),
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_count": 1,
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "no_write_ledger_retention_proof_count": 1,
            "no_write_ledger_retention_proof_field_count": len(retention_fields),
            "ledger_retention_write_locked_count": 1,
            "ledger_retention_write_allowed_count": 0,
            "ledger_retention_written_count": 0,
            "storage_boundary_write_allowed_count": 0,
            "storage_boundary_written_count": 0,
            "ledger_write_allowed_count": 0,
            "ledger_written_count": 0,
            "receipt_persistence_storage_write_allowed_count": 0,
            "receipt_persistence_storage_written_count": 0,
            "verifier_receipt_persistence_allowed_count": 0,
            "verifier_receipt_persisted_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(retention_closeout_result.get("success")),
        "generated_at": retention_closeout_result.get("generated_at"),
        "source_policy": retention_closeout_result.get("policy"),
        "stats": retention_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof": (
            future_database_apply_controlled_dry_run_no_write_ledger_retention_proof
        ),
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout": (
            controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout
        ),
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract": (
            controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract
        ),
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract": (
            ledger_contract
        ),
        "source_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout": (
            ledger_closeout
        ),
        "source_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof": (
            future_ledger
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future no-write ledger retention proof closeout.",
            "Keep ledger retention writes disabled until a later retention boundary closeout proves the retention path.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, ledger writes, ledger retention writes, verifier invocation, verifier receipt persistence, receipt storage, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the retention proof and add a no-write archive proof."""
    archive_closeout_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_retention = (
        archive_closeout_result.get(
            "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        )
        or {}
    )
    retention_closeout = (
        archive_closeout_result.get(
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
        )
        or {}
    )
    retention_contract = (
        archive_closeout_result.get(
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract"
        )
        or {}
    )
    summary = archive_closeout_result.get("summary") or {}
    safety = archive_closeout_result.get("safety") or {}
    retention_proof = retention_closeout.get("no_write_ledger_retention_proof") or {}
    no_write_ledger_proof = (
        retention_closeout.get("storage_boundary_no_write_ledger_proof") or {}
    )
    previous_ledger_closeout = (
        retention_closeout.get(
            "receipt_persistence_storage_boundary_proof_closeout"
        )
        or {}
    )
    rollback_binding = retention_closeout.get("rollback_binding") or {}
    verifier_binding = retention_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = retention_closeout.get(
        "storage_boundary_no_write_ledger_proof_closeout_id"
    )
    source_retention_id = retention_proof.get("retention_proof_id")
    source_ledger_id = retention_proof.get(
        "source_storage_boundary_no_write_ledger_proof_id"
    )
    source_storage_closeout_id = retention_proof.get(
        "source_receipt_persistence_storage_boundary_proof_closeout_id"
    )
    source_storage_id = retention_proof.get(
        "source_receipt_persistence_storage_boundary_proof_id"
    )
    source_guard_closeout_id = retention_proof.get(
        "source_verifier_receipt_persistence_guard_proof_closeout_id"
    )
    source_guard_id = retention_proof.get(
        "source_verifier_receipt_persistence_guard_proof_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout_id(
            archive_closeout_result
        )
    )
    archive_id = f"{closeout_id}-retention-boundary-no-write-archive-proof"
    closeout_fields = [
        "no_write_ledger_retention_proof_closeout_id",
        "source_storage_boundary_no_write_ledger_proof_closeout_id",
        "source_no_write_ledger_retention_proof_id",
        "source_storage_boundary_no_write_ledger_proof_id",
        "source_receipt_persistence_storage_boundary_proof_closeout_id",
        "retention_boundary_no_write_archive_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "retention_archive_write_locked",
        "abort_conditions",
    ]
    acceptance_gates = [
        "storage_boundary_no_write_ledger_proof_closeout_ready",
        "source_chain_ids_match",
        "no_write_ledger_retention_proof_ready",
        "no_write_ledger_retention_proof_no_write",
        "retention_boundary_no_write_archive_proof_bound",
        "retention_boundary_no_write_archive_proof_blocks_archive",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_secret_signature_archive_retention_ledger_storage_persistence_or_database_apply",
    ]
    archive_fields = [
        "archive_proof_id",
        "source_no_write_ledger_retention_proof_closeout_id",
        "source_no_write_ledger_retention_proof_id",
        "source_storage_boundary_no_write_ledger_proof_closeout_id",
        "source_storage_boundary_no_write_ledger_proof_id",
        "archive_mode",
        "retention_archive_write_locked",
        "retention_archive_write_allowed",
        "retention_archive_written",
        "ledger_retention_write_allowed",
        "sql_execution_allowed",
        "database_apply_authorized",
    ]
    abort_conditions = [
        "abort_if_storage_boundary_no_write_ledger_proof_closeout_not_ready",
        "abort_if_source_chain_ids_do_not_match",
        "abort_if_no_write_ledger_retention_proof_missing",
        "abort_if_no_write_ledger_retention_allows_write",
        "abort_if_retention_boundary_no_write_archive_proof_missing",
        "abort_if_retention_boundary_archive_allows_write",
        "abort_if_retention_archive_or_ledger_written",
        "abort_if_endpoint_or_sql_execution_is_allowed",
        "abort_if_database_write_or_apply_is_allowed",
        "abort_if_target_migration_hash_changes",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_signature_archive_retention_ledger_storage_persistence_or_apply_material_is_present",
    ]
    archive_proof = {
        "archive_proof_id": archive_id,
        "source_no_write_ledger_retention_proof_closeout_id": closeout_id,
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_closeout_id
        ),
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": retention_proof.get(
            "required_command_shape_hash"
        ),
        "archive_status": "retention_boundary_no_write_archive_proof_preview_ready",
        "archive_mode": "retention_boundary_no_write_archive_proof_preview_only",
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "archive_receipt_present": False,
        "archive_receipt_required": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "retention_receipt_present": False,
        "retention_receipt_required": False,
        "storage_boundary_write_locked": True,
        "storage_boundary_write_allowed": False,
        "storage_boundary_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "ledger_receipt_present": False,
        "ledger_receipt_required": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_receipt_present": False,
        "verifier_receipt_required": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_database_apply_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "retention_boundary_no_write_archive_proof_field_count": len(
            archive_fields
        ),
        "retention_boundary_no_write_archive_proof_fields": archive_fields,
    }
    retention_closeout_ready = (
        archive_closeout_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT_READY"
        and summary.get(
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count"
        )
        == 1
        and summary.get(
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_pass_count"
        )
        == summary.get(
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check_count"
        )
    )
    source_chain_ids_match = (
        bool(source_closeout_id)
        and source_closeout_id
        == future_retention.get(
            "storage_boundary_no_write_ledger_proof_closeout_id"
        )
        == retention_proof.get(
            "source_storage_boundary_no_write_ledger_proof_closeout_id"
        )
        == archive_proof.get(
            "source_storage_boundary_no_write_ledger_proof_closeout_id"
        )
        and source_retention_id
        == future_retention.get("no_write_ledger_retention_proof_id")
        == archive_proof.get("source_no_write_ledger_retention_proof_id")
        and source_ledger_id
        == future_retention.get("source_storage_boundary_no_write_ledger_proof_id")
        == no_write_ledger_proof.get("ledger_proof_id")
        == archive_proof.get("source_storage_boundary_no_write_ledger_proof_id")
        and source_storage_closeout_id
        == future_retention.get(
            "source_receipt_persistence_storage_boundary_proof_closeout_id"
        )
        == archive_proof.get(
            "source_receipt_persistence_storage_boundary_proof_closeout_id"
        )
        and source_storage_id
        == future_retention.get("source_receipt_persistence_storage_boundary_proof_id")
        == archive_proof.get("source_receipt_persistence_storage_boundary_proof_id")
        and source_guard_closeout_id
        == future_retention.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        == archive_proof.get(
            "source_verifier_receipt_persistence_guard_proof_closeout_id"
        )
        and source_guard_id
        == future_retention.get("source_verifier_receipt_persistence_guard_proof_id")
        == archive_proof.get("source_verifier_receipt_persistence_guard_proof_id")
        and retention_proof.get("required_command_shape_hash")
        == no_write_ledger_proof.get("required_command_shape_hash")
        == archive_proof.get("required_command_shape_hash")
    )
    retention_proof_ready = (
        retention_closeout_ready
        and retention_proof.get("retention_status")
        == "no_write_ledger_retention_proof_preview_ready"
        and retention_proof.get("retention_proof_id")
        == future_retention.get("no_write_ledger_retention_proof_id")
        and int(
            retention_proof.get("no_write_ledger_retention_proof_field_count")
            or 0
        )
        == 12
        and summary.get("no_write_ledger_retention_proof_count") == 1
    )
    retention_proof_no_write = (
        retention_proof.get("retention_mode")
        == "no_write_ledger_retention_proof_preview_only"
        and retention_proof.get("ledger_retention_write_locked") is True
        and retention_proof.get("ledger_retention_write_allowed") is False
        and retention_proof.get("ledger_retention_written") is False
        and retention_proof.get("ledger_write_allowed") is False
        and retention_proof.get("ledger_written") is False
        and retention_proof.get("receipt_persistence_storage_write_allowed")
        is False
        and retention_proof.get("receipt_persistence_storage_written") is False
        and retention_proof.get("verifier_receipt_persistence_allowed") is False
        and retention_proof.get("verifier_receipt_persisted") is False
        and retention_proof.get("persists_verifier_receipt") is False
        and retention_proof.get("verifier_invoked") is False
        and retention_proof.get("dry_run_executor_invoked") is False
        and retention_proof.get("runner_invocation_performed") is False
        and retention_proof.get("endpoint_executed") is False
        and retention_proof.get("sql_executed") is False
        and retention_proof.get("database_written") is False
        and retention_proof.get("endpoint_execution_allowed") is False
        and retention_proof.get("sql_execution_allowed") is False
        and retention_proof.get("database_write_allowed") is False
        and retention_proof.get("database_apply_authorized") is False
        and retention_proof.get("executes_database_apply") is False
        and retention_proof.get("executes_endpoint") is False
        and retention_proof.get("executes_sql") is False
        and retention_proof.get("writes_database") is False
        and retention_proof.get("stdout_included") is False
        and retention_proof.get("stderr_included") is False
    )
    archive_bound = (
        retention_proof_ready
        and bool(archive_proof.get("archive_proof_id"))
        and archive_proof.get(
            "source_no_write_ledger_retention_proof_closeout_id"
        )
        == closeout_id
        and archive_proof.get("source_no_write_ledger_retention_proof_id")
        == source_retention_id
        and archive_proof.get(
            "source_storage_boundary_no_write_ledger_proof_closeout_id"
        )
        == source_closeout_id
        and archive_proof.get("source_storage_boundary_no_write_ledger_proof_id")
        == source_ledger_id
        and archive_proof.get("required_command_shape_hash")
        == retention_proof.get("required_command_shape_hash")
        and int(
            archive_proof.get(
                "retention_boundary_no_write_archive_proof_field_count"
            )
            or 0
        )
        == len(archive_fields)
    )
    archive_blocks_write = (
        archive_proof.get("archive_mode")
        == "retention_boundary_no_write_archive_proof_preview_only"
        and archive_proof.get("retention_archive_write_locked") is True
        and archive_proof.get("retention_archive_write_allowed") is False
        and archive_proof.get("retention_archive_written") is False
        and archive_proof.get("ledger_retention_write_allowed") is False
        and archive_proof.get("ledger_retention_written") is False
        and archive_proof.get("ledger_write_allowed") is False
        and archive_proof.get("ledger_written") is False
        and archive_proof.get("receipt_persistence_storage_write_allowed") is False
        and archive_proof.get("receipt_persistence_storage_written") is False
        and archive_proof.get("verifier_receipt_persistence_allowed") is False
        and archive_proof.get("verifier_receipt_persisted") is False
        and archive_proof.get("persists_verifier_receipt") is False
        and archive_proof.get("verifier_invoked") is False
        and archive_proof.get("dry_run_executor_invoked") is False
        and archive_proof.get("runner_invocation_performed") is False
        and archive_proof.get("endpoint_executed") is False
        and archive_proof.get("sql_executed") is False
        and archive_proof.get("database_written") is False
        and archive_proof.get("endpoint_execution_allowed") is False
        and archive_proof.get("sql_execution_allowed") is False
        and archive_proof.get("database_write_allowed") is False
        and archive_proof.get("database_apply_authorized") is False
        and archive_proof.get("executes_database_apply") is False
        and archive_proof.get("executes_endpoint") is False
        and archive_proof.get("executes_sql") is False
        and archive_proof.get("writes_database") is False
        and archive_proof.get("stdout_included") is False
        and archive_proof.get("stderr_included") is False
    )
    previous_closeouts_carried_forward = (
        retention_closeout.get("storage_boundary_no_write_ledger_proof_closeout_only")
        is True
        and retention_closeout.get("no_write_ledger_retention_proof_only")
        is True
        and previous_ledger_closeout.get(
            "receipt_persistence_storage_boundary_proof_closeout_only"
        )
        is True
        and retention_proof_no_write
    )
    target_hash_locked = (
        retention_closeout.get("target_file")
        == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
        and bool(retention_closeout.get("expected_sha256"))
        and bool(retention_closeout.get("actual_sha256"))
        and retention_closeout.get("expected_sha256")
        == retention_closeout.get("actual_sha256")
        and retention_closeout.get("hash_matches") is True
        and retention_closeout.get("target_migration_hash_locked") is True
    )
    rollback_and_verifier_bound = (
        bool(rollback_binding.get("rollback_binding_id"))
        and rollback_binding.get("rollback_execution_authorized") is False
        and rollback_binding.get("rollback_executes_sql") is False
        and rollback_binding.get("rollback_writes_database") is False
        and bool(verifier_binding.get("post_apply_verifier_binding_id"))
        and verifier_binding.get("verifier_must_run_after_apply") is True
        and verifier_binding.get("verifier_execution_authorized_in_preview")
        is False
        and verifier_binding.get("database_apply_authorized") is False
    )
    contract_blocks_archive_retention_storage_persistence_and_apply = (
        retention_contract.get(
            "permits_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        )
        is True
        and retention_contract.get("ledger_retention_write_allowed") is False
        and retention_contract.get("ledger_retention_written") is False
        and retention_contract.get("ledger_write_allowed") is False
        and retention_contract.get("ledger_written") is False
        and retention_contract.get("receipt_persistence_storage_write_allowed")
        is False
        and retention_contract.get("receipt_persistence_storage_written") is False
        and retention_contract.get("persists_verifier_receipt") is False
        and retention_contract.get("executes_database_apply") is False
        and retention_contract.get("database_apply_authorized") is False
        and retention_contract.get("writes_database") is False
    )
    side_effect_free = (
        summary.get("reads_secret_count", 0) == 0
        and summary.get("executes_endpoint_count", 0) == 0
        and summary.get("executes_sql_count", 0) == 0
        and summary.get("writes_database_count", 0) == 0
        and summary.get("signs_database_apply_authorization_count", 0) == 0
        and summary.get("ledger_retention_write_allowed_count", 0) == 0
        and summary.get("ledger_retention_written_count", 0) == 0
        and summary.get("ledger_write_allowed_count", 0) == 0
        and summary.get("ledger_written_count", 0) == 0
        and summary.get("receipt_persistence_storage_write_allowed_count", 0) == 0
        and summary.get("receipt_persistence_storage_written_count", 0) == 0
        and summary.get("persists_verifier_receipt_count", 0) == 0
        and safety.get("persists_verifier_receipt") is False
    )
    checks = [
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "storage_boundary_no_write_ledger_proof_closeout_ready",
            retention_closeout_ready,
            {
                "result": archive_closeout_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count"
                ),
            },
            "wait_for_storage_boundary_no_write_ledger_proof_closeout",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "source_chain_ids_match",
            source_chain_ids_match,
            {
                "source_closeout_id": source_closeout_id,
                "source_retention_id": source_retention_id,
                "source_ledger_id": source_ledger_id,
                "source_storage_closeout_id": source_storage_closeout_id,
            },
            "wait_for_source_chain_alignment",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "no_write_ledger_retention_proof_ready",
            retention_proof_ready,
            {
                "retention_proof_id": source_retention_id,
                "retention_status": retention_proof.get("retention_status"),
                "field_count": retention_proof.get(
                    "no_write_ledger_retention_proof_field_count"
                ),
            },
            "wait_for_no_write_ledger_retention_proof",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "no_write_ledger_retention_proof_no_write",
            retention_proof_no_write,
            {
                "retention_mode": retention_proof.get("retention_mode"),
                "ledger_retention_write_allowed": retention_proof.get(
                    "ledger_retention_write_allowed"
                ),
                "database_apply_authorized": retention_proof.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_no_write_ledger_retention_allows_write",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "retention_boundary_no_write_archive_proof_bound",
            archive_bound,
            {
                "archive_proof_id": archive_id,
                "source_no_write_ledger_retention_proof_id": source_retention_id,
                "field_count": archive_proof.get(
                    "retention_boundary_no_write_archive_proof_field_count"
                ),
            },
            "wait_for_retention_boundary_no_write_archive_proof",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "retention_boundary_no_write_archive_proof_blocks_archive",
            archive_blocks_write,
            {
                "archive_mode": archive_proof.get("archive_mode"),
                "retention_archive_write_allowed": archive_proof.get(
                    "retention_archive_write_allowed"
                ),
                "retention_archive_written": archive_proof.get(
                    "retention_archive_written"
                ),
            },
            "abort_if_retention_boundary_archive_allows_write",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "source_closeout_only": retention_closeout.get(
                    "storage_boundary_no_write_ledger_proof_closeout_only"
                ),
                "source_retention_only": retention_closeout.get(
                    "no_write_ledger_retention_proof_only"
                ),
            },
            "wait_for_previous_closeouts",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": retention_closeout.get("target_file"),
                "hash_matches": retention_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    retention_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(retention_closeout.get("actual_sha256")),
            },
            "require_target_migration_hash_lock",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "storage_boundary_no_write_ledger_proof_closeout_contract_blocks_archive_retention_storage_persistence_and_database_apply",
            contract_blocks_archive_retention_storage_persistence_and_apply,
            {
                "permits_future_no_write_ledger_retention_proof": retention_contract.get(
                    "permits_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
                ),
                "ledger_retention_write_allowed": retention_contract.get(
                    "ledger_retention_write_allowed"
                ),
                "database_apply_authorized": retention_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_archive_retention_storage_persistence_or_database_apply",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "preview_has_no_side_effects_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "ledger_retention_written_count": summary.get(
                    "ledger_retention_written_count", 0
                ),
            },
            "abort_on_preview_archive_retention_ledger_storage_persistence_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_no_write_ledger_retention_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            retention_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": retention_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof = {
        "no_write_ledger_retention_proof_closeout_id": closeout_id,
        "retention_boundary_no_write_archive_proof_id": archive_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_closeout_id
        ),
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout": (
            closeout_ready
        ),
        "no_write_ledger_retention_proof_closeout_ready": closeout_ready,
        "storage_boundary_no_write_ledger_proof_closeout_ready": (
            retention_closeout_ready
        ),
        "no_write_ledger_retention_proof_ready": retention_proof_ready,
        "retention_boundary_no_write_archive_proof_bound": closeout_ready,
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_no_write_ledger_retention_proof_closeout = {
        "no_write_ledger_retention_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_no_write_ledger_retention_proof_closeout"
        ),
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_closeout_id
        ),
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": source_storage_id,
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": retention_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof": (
            closeout_ready
        ),
        "no_write_ledger_retention_proof_closeout_fields": closeout_fields,
        "no_write_ledger_retention_proof_closeout_field_count": len(
            closeout_fields
        ),
        "no_write_ledger_retention_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "no_write_ledger_retention_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "retention_boundary_no_write_archive_proof": archive_proof,
        "retention_boundary_no_write_archive_proof_count": 1,
        "retention_boundary_no_write_archive_proof_field_count": len(
            archive_fields
        ),
        "no_write_ledger_retention_proof": retention_proof,
        "no_write_ledger_retention_proof_count": 1,
        "storage_boundary_no_write_ledger_proof_closeout": retention_closeout,
        "storage_boundary_no_write_ledger_proof_closeout_count": 1,
        "storage_boundary_no_write_ledger_proof": no_write_ledger_proof,
        "storage_boundary_no_write_ledger_proof_count": 1,
        "target_file": retention_closeout.get("target_file"),
        "expected_sha256": retention_closeout.get("expected_sha256"),
        "actual_sha256": retention_closeout.get("actual_sha256"),
        "hash_matches": retention_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "no_write_ledger_retention_proof_closeout_only": True,
        "retention_boundary_no_write_archive_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_no_write_ledger_retention_proof_closeout_contract = {
        "mode": "controlled_dry_run_no_write_ledger_retention_proof_closeout_and_retention_boundary_no_write_archive_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-write-ledger-retention-proof-closeout"
        ),
        "source_storage_boundary_no_write_ledger_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-storage-boundary-no-write-ledger-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof": (
            closeout_ready
        ),
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_count": 1,
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "retention_boundary_no_write_archive_proof_count": 1,
            "retention_boundary_no_write_archive_proof_field_count": len(
                archive_fields
            ),
            "retention_archive_write_locked_count": 1,
            "retention_archive_write_allowed_count": 0,
            "retention_archive_written_count": 0,
            "ledger_retention_write_allowed_count": 0,
            "ledger_retention_written_count": 0,
            "storage_boundary_write_allowed_count": 0,
            "storage_boundary_written_count": 0,
            "ledger_write_allowed_count": 0,
            "ledger_written_count": 0,
            "receipt_persistence_storage_write_allowed_count": 0,
            "receipt_persistence_storage_written_count": 0,
            "verifier_receipt_persistence_allowed_count": 0,
            "verifier_receipt_persisted_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(archive_closeout_result.get("success")),
        "generated_at": archive_closeout_result.get("generated_at"),
        "source_policy": archive_closeout_result.get("policy"),
        "stats": archive_closeout_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof": (
            future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof
        ),
        "controlled_dry_run_no_write_ledger_retention_proof_closeout": (
            controlled_dry_run_no_write_ledger_retention_proof_closeout
        ),
        "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract": (
            controlled_dry_run_no_write_ledger_retention_proof_closeout_contract
        ),
        "controlled_dry_run_no_write_ledger_retention_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract": (
            retention_contract
        ),
        "source_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout": (
            retention_closeout
        ),
        "source_database_apply_controlled_dry_run_no_write_ledger_retention_proof": (
            future_retention
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future retention boundary no-write archive proof closeout.",
            "Keep retention archive writes disabled until a later archive boundary closeout proves the archive path.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, archive writes, ledger writes, ledger retention writes, verifier invocation, verifier receipt persistence, receipt storage, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the archive proof into a sealed no-write handoff proof."""
    sealed_handoff_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_archive = (
        sealed_handoff_result.get(
            "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        )
        or {}
    )
    archive_closeout = (
        sealed_handoff_result.get(
            "controlled_dry_run_no_write_ledger_retention_proof_closeout"
        )
        or {}
    )
    archive_contract = (
        sealed_handoff_result.get(
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract"
        )
        or {}
    )
    summary = sealed_handoff_result.get("summary") or {}
    safety = sealed_handoff_result.get("safety") or {}
    archive_proof = (
        archive_closeout.get("retention_boundary_no_write_archive_proof") or {}
    )
    retention_proof = archive_closeout.get("no_write_ledger_retention_proof") or {}
    previous_retention_closeout = (
        archive_closeout.get("storage_boundary_no_write_ledger_proof_closeout")
        or {}
    )
    rollback_binding = archive_closeout.get("rollback_binding") or {}
    verifier_binding = archive_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = archive_closeout.get(
        "no_write_ledger_retention_proof_closeout_id"
    )
    source_archive_id = archive_proof.get("archive_proof_id")
    source_retention_id = archive_proof.get("source_no_write_ledger_retention_proof_id")
    source_storage_closeout_id = archive_proof.get(
        "source_storage_boundary_no_write_ledger_proof_closeout_id"
    )
    source_ledger_id = archive_proof.get(
        "source_storage_boundary_no_write_ledger_proof_id"
    )
    source_receipt_storage_closeout_id = archive_proof.get(
        "source_receipt_persistence_storage_boundary_proof_closeout_id"
    )
    source_receipt_storage_id = archive_proof.get(
        "source_receipt_persistence_storage_boundary_proof_id"
    )
    source_guard_closeout_id = archive_proof.get(
        "source_verifier_receipt_persistence_guard_proof_closeout_id"
    )
    source_guard_id = archive_proof.get(
        "source_verifier_receipt_persistence_guard_proof_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_id(
            sealed_handoff_result
        )
    )
    handoff_id = f"{closeout_id}-archive-retention-sealed-handoff-proof"
    closeout_fields = [
        "retention_boundary_no_write_archive_proof_closeout_id",
        "source_no_write_ledger_retention_proof_closeout_id",
        "source_retention_boundary_no_write_archive_proof_id",
        "source_no_write_ledger_retention_proof_id",
        "source_storage_boundary_no_write_ledger_proof_closeout_id",
        "archive_retention_sealed_handoff_proof_id",
        "required_command_shape_hash",
        "target_migration_file",
        "expected_sha256",
        "actual_sha256",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
    ]
    handoff_fields = [
        "archive_retention_sealed_handoff_proof_id",
        "source_no_write_ledger_retention_proof_closeout_id",
        "source_retention_boundary_no_write_archive_proof_id",
        "source_no_write_ledger_retention_proof_id",
        "source_storage_boundary_no_write_ledger_proof_closeout_id",
        "required_command_shape_hash",
        "target_migration_file",
        "expected_sha256",
        "actual_sha256",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "sealed_handoff_manifest_hash",
    ]
    acceptance_gates = [
        "no_write_ledger_retention_proof_closeout_ready",
        "retention_boundary_no_write_archive_proof_ready",
        "retention_boundary_no_write_archive_proof_no_write",
        "archive_retention_sealed_handoff_proof_bound",
        "archive_retention_sealed_handoff_proof_blocks_handoff_write",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "no_write_ledger_retention_proof_closeout_contract_blocks_handoff_archive_retention_storage_persistence_and_database_apply",
        "preview_has_no_side_effects_no_handoff_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing",
    ]
    abort_conditions = [
        "abort_if_no_write_ledger_retention_proof_closeout_not_ready",
        "abort_if_retention_boundary_archive_proof_missing",
        "abort_if_retention_boundary_archive_write_allowed_or_written",
        "abort_if_sealed_handoff_write_allowed_or_written",
        "abort_if_previous_closeout_ids_do_not_match",
        "abort_if_target_migration_hash_is_not_locked",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_or_signature_material_is_included",
        "abort_if_any_endpoint_sql_database_runner_verifier_or_executor_action_is_allowed",
        "abort_if_manual_review_mode_is_not_exception_only",
    ]
    archive_closeout_ready = (
        sealed_handoff_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT_READY"
        and archive_closeout.get(
            "ready_for_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        )
        is True
    )
    archive_proof_ready = (
        archive_proof.get("archive_status")
        == "retention_boundary_no_write_archive_proof_preview_ready"
        and archive_proof.get("archive_mode")
        == "retention_boundary_no_write_archive_proof_preview_only"
        and archive_proof.get("retention_boundary_no_write_archive_proof_field_count")
        == 12
    )
    archive_no_write = (
        archive_proof.get("retention_archive_write_locked") is True
        and archive_proof.get("retention_archive_write_allowed") is False
        and archive_proof.get("retention_archive_written") is False
        and archive_proof.get("ledger_retention_write_allowed") is False
        and archive_proof.get("ledger_retention_written") is False
        and archive_proof.get("ledger_write_allowed") is False
        and archive_proof.get("ledger_written") is False
        and archive_proof.get("receipt_persistence_storage_write_allowed") is False
        and archive_proof.get("receipt_persistence_storage_written") is False
        and archive_proof.get("persists_verifier_receipt") is False
        and archive_proof.get("endpoint_executed") is False
        and archive_proof.get("sql_executed") is False
        and archive_proof.get("database_written") is False
        and archive_proof.get("database_apply_authorized") is False
    )
    target_hash_locked = (
        bool(archive_closeout.get("target_file"))
        and bool(archive_closeout.get("expected_sha256"))
        and bool(archive_closeout.get("actual_sha256"))
        and archive_closeout.get("expected_sha256")
        == archive_closeout.get("actual_sha256")
        and archive_closeout.get("hash_matches") is True
    )
    rollback_and_verifier_bound = bool(
        rollback_binding.get("rollback_binding_id")
    ) and bool(verifier_binding.get("post_apply_verifier_binding_id"))
    previous_closeouts_carried_forward = (
        archive_closeout.get("no_write_ledger_retention_proof_closeout_only")
        is True
        and archive_closeout.get("retention_boundary_no_write_archive_proof_only")
        is True
        and archive_proof.get("source_no_write_ledger_retention_proof_closeout_id")
        == source_closeout_id
        and archive_proof.get("source_no_write_ledger_retention_proof_id")
        == source_retention_id
        and archive_proof.get("source_storage_boundary_no_write_ledger_proof_closeout_id")
        == source_storage_closeout_id
    )
    contract_blocks_handoff_archive_retention_storage_persistence_and_apply = (
        archive_contract.get(
            "permits_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        )
        is True
        and archive_contract.get("retention_archive_write_allowed") is False
        and archive_contract.get("ledger_retention_write_allowed") is False
        and archive_contract.get("ledger_write_allowed") is False
        and archive_contract.get("receipt_persistence_storage_write_allowed") is False
        and archive_contract.get("persists_verifier_receipt") is False
        and archive_contract.get("executes_database_apply") is False
        and archive_contract.get("database_apply_authorized") is False
        and archive_contract.get("writes_database") is False
    )
    handoff_manifest = {
        "source_no_write_ledger_retention_proof_closeout_id": source_closeout_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "target_file": archive_closeout.get("target_file"),
        "expected_sha256": archive_closeout.get("expected_sha256"),
        "actual_sha256": archive_closeout.get("actual_sha256"),
        "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
        "post_apply_verifier_binding_id": verifier_binding.get(
            "post_apply_verifier_binding_id"
        ),
        "manual_review_mode": "exception_only",
    }
    handoff_manifest_hash = hashlib.sha256(
        json.dumps(handoff_manifest, sort_keys=True).encode("utf-8")
    ).hexdigest()
    handoff_bound = (
        archive_closeout_ready
        and archive_proof_ready
        and bool(source_closeout_id)
        and bool(source_archive_id)
        and bool(source_retention_id)
        and len(handoff_fields) == 12
        and bool(handoff_manifest_hash)
    )
    handoff_write_blocked = True
    nonsecret_machine_readable_handoff = (
        handoff_bound
        and bool(handoff_manifest_hash)
        and handoff_manifest.get("manual_review_mode") == "exception_only"
    )
    side_effect_free = (
        int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("retention_archive_written_count") or 0) == 0
        and int(summary.get("ledger_retention_written_count") or 0) == 0
        and int(summary.get("ledger_written_count") or 0) == 0
        and int(summary.get("receipt_persistence_storage_written_count") or 0) == 0
        and int(summary.get("persists_verifier_receipt_count") or 0) == 0
        and int(summary.get("verifier_invoked_count") or 0) == 0
        and int(summary.get("dry_run_executor_invoked_count") or 0) == 0
        and int(summary.get("runner_invocation_performed_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and archive_proof.get("retention_archive_written") is False
        and archive_proof.get("database_written") is False
        and archive_proof.get("database_apply_authorized") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
    )
    archive_retention_sealed_handoff_proof = {
        "archive_retention_sealed_handoff_proof_id": handoff_id,
        "authorization_material_type": (
            "controlled_dry_run_archive_retention_sealed_handoff_proof"
        ),
        "source_no_write_ledger_retention_proof_closeout_id": source_closeout_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_receipt_storage_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": (
            source_receipt_storage_id
        ),
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": archive_proof.get(
            "required_command_shape_hash"
        ),
        "target_file": archive_closeout.get("target_file"),
        "expected_sha256": archive_closeout.get("expected_sha256"),
        "actual_sha256": archive_closeout.get("actual_sha256"),
        "hash_matches": archive_closeout.get("hash_matches"),
        "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
        "post_apply_verifier_binding_id": verifier_binding.get(
            "post_apply_verifier_binding_id"
        ),
        "sealed_handoff_manifest": handoff_manifest,
        "sealed_handoff_manifest_hash": handoff_manifest_hash,
        "handoff_status": "archive_retention_sealed_handoff_proof_preview_ready",
        "handoff_mode": "archive_retention_sealed_handoff_proof_preview_only",
        "archive_retention_sealed_handoff_proof_fields": handoff_fields,
        "archive_retention_sealed_handoff_proof_field_count": len(handoff_fields),
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    checks = [
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "no_write_ledger_retention_proof_closeout_ready",
            archive_closeout_ready,
            {
                "result": sealed_handoff_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_count"
                ),
            },
            "wait_for_no_write_ledger_retention_proof_closeout",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "retention_boundary_no_write_archive_proof_ready",
            archive_proof_ready,
            {
                "archive_status": archive_proof.get("archive_status"),
                "archive_mode": archive_proof.get("archive_mode"),
                "field_count": archive_proof.get(
                    "retention_boundary_no_write_archive_proof_field_count"
                ),
            },
            "wait_for_retention_boundary_no_write_archive_proof",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "retention_boundary_no_write_archive_proof_no_write",
            archive_no_write,
            {
                "retention_archive_write_allowed": archive_proof.get(
                    "retention_archive_write_allowed"
                ),
                "retention_archive_written": archive_proof.get(
                    "retention_archive_written"
                ),
                "database_written": archive_proof.get("database_written"),
                "database_apply_authorized": archive_proof.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_archive_retention_storage_persistence_or_database_apply_allowed",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "archive_retention_sealed_handoff_proof_bound",
            handoff_bound,
            {
                "handoff_id": handoff_id,
                "source_archive_id": source_archive_id,
                "source_closeout_id": source_closeout_id,
                "field_count": len(handoff_fields),
            },
            "wait_for_archive_retention_sealed_handoff_proof",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "archive_retention_sealed_handoff_proof_blocks_handoff_write",
            handoff_write_blocked,
            {
                "handoff_mode": archive_retention_sealed_handoff_proof.get(
                    "handoff_mode"
                ),
                "sealed_handoff_write_allowed": False,
                "sealed_handoff_written": False,
            },
            "abort_if_sealed_handoff_write_allowed_or_written",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "source_closeout_only": archive_closeout.get(
                    "no_write_ledger_retention_proof_closeout_only"
                ),
                "source_archive_only": archive_closeout.get(
                    "retention_boundary_no_write_archive_proof_only"
                ),
                "source_previous_closeout_id": previous_retention_closeout.get(
                    "storage_boundary_no_write_ledger_proof_closeout_id"
                ),
            },
            "wait_for_previous_closeout_chain",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": archive_closeout.get("target_file"),
                "hash_matches": archive_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    archive_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(
                    archive_closeout.get("actual_sha256")
                ),
            },
            "wait_for_target_migration_hash_lock",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "no_write_ledger_retention_proof_closeout_contract_blocks_handoff_archive_retention_storage_persistence_and_database_apply",
            contract_blocks_handoff_archive_retention_storage_persistence_and_apply,
            {
                "permits_future_archive_proof": archive_contract.get(
                    "permits_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
                ),
                "retention_archive_write_allowed": archive_contract.get(
                    "retention_archive_write_allowed"
                ),
                "database_apply_authorized": archive_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_handoff_archive_retention_storage_persistence_or_database_apply",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "sealed_handoff_has_nonsecret_machine_readable_manifest",
            nonsecret_machine_readable_handoff,
            {
                "manifest_hash_present": bool(handoff_manifest_hash),
                "accepts_plaintext_secret": archive_retention_sealed_handoff_proof.get(
                    "accepts_plaintext_secret"
                ),
                "secret_material_included": archive_retention_sealed_handoff_proof.get(
                    "secret_material_included"
                ),
                "signature_material_included": archive_retention_sealed_handoff_proof.get(
                    "signature_material_included"
                ),
            },
            "abort_if_sealed_handoff_manifest_contains_secret_signature_or_is_not_machine_readable",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "preview_has_no_side_effects_no_handoff_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "retention_archive_written_count": summary.get(
                    "retention_archive_written_count", 0
                ),
            },
            "abort_on_preview_handoff_archive_retention_ledger_storage_persistence_side_effect_execution_or_signing",
        ),
        _controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            archive_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": archive_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_RETENTION_BOUNDARY_NO_WRITE_ARCHIVE_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof = {
        "retention_boundary_no_write_archive_proof_closeout_id": closeout_id,
        "archive_retention_sealed_handoff_proof_id": handoff_id,
        "source_no_write_ledger_retention_proof_closeout_id": source_closeout_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_receipt_storage_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": (
            source_receipt_storage_id
        ),
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout": (
            closeout_ready
        ),
        "retention_boundary_no_write_archive_proof_closeout_ready": closeout_ready,
        "no_write_ledger_retention_proof_closeout_ready": archive_closeout_ready,
        "retention_boundary_no_write_archive_proof_ready": archive_proof_ready,
        "archive_retention_sealed_handoff_proof_bound": closeout_ready,
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    controlled_dry_run_retention_boundary_no_write_archive_proof_closeout = {
        "retention_boundary_no_write_archive_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
        ),
        "source_no_write_ledger_retention_proof_closeout_id": source_closeout_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "source_no_write_ledger_retention_proof_id": source_retention_id,
        "source_storage_boundary_no_write_ledger_proof_closeout_id": (
            source_storage_closeout_id
        ),
        "source_storage_boundary_no_write_ledger_proof_id": source_ledger_id,
        "source_receipt_persistence_storage_boundary_proof_closeout_id": (
            source_receipt_storage_closeout_id
        ),
        "source_receipt_persistence_storage_boundary_proof_id": (
            source_receipt_storage_id
        ),
        "source_verifier_receipt_persistence_guard_proof_closeout_id": (
            source_guard_closeout_id
        ),
        "source_verifier_receipt_persistence_guard_proof_id": source_guard_id,
        "required_command_shape_hash": archive_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof": (
            closeout_ready
        ),
        "retention_boundary_no_write_archive_proof_closeout_fields": (
            closeout_fields
        ),
        "retention_boundary_no_write_archive_proof_closeout_field_count": len(
            closeout_fields
        ),
        "retention_boundary_no_write_archive_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "retention_boundary_no_write_archive_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "archive_retention_sealed_handoff_proof": (
            archive_retention_sealed_handoff_proof
        ),
        "archive_retention_sealed_handoff_proof_count": 1,
        "archive_retention_sealed_handoff_proof_field_count": len(handoff_fields),
        "retention_boundary_no_write_archive_proof": archive_proof,
        "retention_boundary_no_write_archive_proof_count": 1,
        "no_write_ledger_retention_proof_closeout": archive_closeout,
        "no_write_ledger_retention_proof_closeout_count": 1,
        "no_write_ledger_retention_proof": retention_proof,
        "no_write_ledger_retention_proof_count": 1,
        "storage_boundary_no_write_ledger_proof_closeout": (
            previous_retention_closeout
        ),
        "storage_boundary_no_write_ledger_proof_closeout_count": 1,
        "target_file": archive_closeout.get("target_file"),
        "expected_sha256": archive_closeout.get("expected_sha256"),
        "actual_sha256": archive_closeout.get("actual_sha256"),
        "hash_matches": archive_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "retention_boundary_no_write_archive_proof_closeout_only": True,
        "archive_retention_sealed_handoff_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_boundary_locked": True,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract = {
        "mode": "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_and_archive_retention_sealed_handoff_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-retention-boundary-no-write-archive-proof-closeout"
        ),
        "source_no_write_ledger_retention_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-no-write-ledger-retention-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof": (
            closeout_ready
        ),
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "retention_archive_write_locked": True,
        "retention_archive_write_allowed": False,
        "retention_archive_written": False,
        "ledger_retention_write_locked": True,
        "ledger_retention_write_allowed": False,
        "ledger_retention_written": False,
        "ledger_write_allowed": False,
        "ledger_written": False,
        "receipt_persistence_storage_write_allowed": False,
        "receipt_persistence_storage_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_retention_boundary_archive_now": False,
        "ready_for_no_write_ledger_retention_now": False,
        "ready_for_storage_boundary_ledger_write_now": False,
        "ready_for_receipt_persistence_storage_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_count": 1,
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "archive_retention_sealed_handoff_proof_count": 1,
            "archive_retention_sealed_handoff_proof_field_count": len(
                handoff_fields
            ),
            "sealed_handoff_write_locked_count": 1,
            "sealed_handoff_write_allowed_count": 0,
            "sealed_handoff_written_count": 0,
            "retention_archive_write_allowed_count": 0,
            "retention_archive_written_count": 0,
            "ledger_retention_write_allowed_count": 0,
            "ledger_retention_written_count": 0,
            "storage_boundary_write_allowed_count": 0,
            "storage_boundary_written_count": 0,
            "ledger_write_allowed_count": 0,
            "ledger_written_count": 0,
            "receipt_persistence_storage_write_allowed_count": 0,
            "receipt_persistence_storage_written_count": 0,
            "verifier_receipt_persistence_allowed_count": 0,
            "verifier_receipt_persisted_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_RETENTION_BOUNDARY_NO_WRITE_ARCHIVE_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(sealed_handoff_result.get("success")),
        "generated_at": sealed_handoff_result.get("generated_at"),
        "source_policy": sealed_handoff_result.get("policy"),
        "stats": sealed_handoff_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof": (
            future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof
        ),
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout": (
            controlled_dry_run_retention_boundary_no_write_archive_proof_closeout
        ),
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract": (
            controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract
        ),
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_no_write_ledger_retention_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_no_write_ledger_retention_proof_closeout_contract": (
            archive_contract
        ),
        "source_controlled_dry_run_no_write_ledger_retention_proof_closeout": (
            archive_closeout
        ),
        "source_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof": (
            future_archive
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future archive retention sealed handoff proof closeout.",
            "Keep sealed handoff writes disabled until a later handoff closeout proves the handoff path.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, archive writes, handoff writes, ledger writes, ledger retention writes, verifier invocation, verifier receipt persistence, receipt storage, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out the sealed handoff proof into a verifier transfer proof."""
    transfer_result = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout(
            payload,
            batch_size=batch_size,
            execute_fetch=execute_fetch,
            timeout_seconds=timeout_seconds,
            http_get=http_get,
        )
    )
    future_handoff = (
        transfer_result.get(
            "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        )
        or {}
    )
    handoff_closeout = (
        transfer_result.get(
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
        )
        or {}
    )
    handoff_contract = (
        transfer_result.get(
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract"
        )
        or {}
    )
    summary = transfer_result.get("summary") or {}
    safety = transfer_result.get("safety") or {}
    handoff_proof = (
        handoff_closeout.get("archive_retention_sealed_handoff_proof") or {}
    )
    archive_proof = (
        handoff_closeout.get("retention_boundary_no_write_archive_proof") or {}
    )
    source_archive_closeout = (
        handoff_closeout.get("no_write_ledger_retention_proof_closeout") or {}
    )
    rollback_binding = handoff_closeout.get("rollback_binding") or {}
    verifier_binding = handoff_closeout.get("post_apply_verifier_binding") or {}
    source_closeout_id = handoff_closeout.get(
        "retention_boundary_no_write_archive_proof_closeout_id"
    )
    source_handoff_id = handoff_proof.get("archive_retention_sealed_handoff_proof_id")
    source_archive_id = handoff_proof.get(
        "source_retention_boundary_no_write_archive_proof_id"
    )
    source_retention_closeout_id = handoff_proof.get(
        "source_no_write_ledger_retention_proof_closeout_id"
    )
    closeout_id = (
        _db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_id(
            transfer_result
        )
    )
    transfer_id = f"{closeout_id}-sealed-handoff-verifier-transfer-proof"
    closeout_fields = [
        "archive_retention_sealed_handoff_proof_closeout_id",
        "source_retention_boundary_no_write_archive_proof_closeout_id",
        "source_archive_retention_sealed_handoff_proof_id",
        "source_retention_boundary_no_write_archive_proof_id",
        "source_no_write_ledger_retention_proof_closeout_id",
        "sealed_handoff_verifier_transfer_proof_id",
        "sealed_handoff_manifest_hash",
        "required_command_shape_hash",
        "target_migration_file",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "verifier_transfer_manifest_hash",
    ]
    transfer_fields = [
        "sealed_handoff_verifier_transfer_proof_id",
        "source_archive_retention_sealed_handoff_proof_closeout_id",
        "source_archive_retention_sealed_handoff_proof_id",
        "source_retention_boundary_no_write_archive_proof_closeout_id",
        "sealed_handoff_manifest_hash",
        "verifier_transfer_manifest_hash",
        "target_migration_file",
        "expected_sha256",
        "actual_sha256",
        "rollback_binding_id",
        "post_apply_verifier_binding_id",
        "verifier_transfer_status",
    ]
    acceptance_gates = [
        "retention_boundary_no_write_archive_proof_closeout_ready",
        "archive_retention_sealed_handoff_proof_ready",
        "sealed_handoff_manifest_hash_locked",
        "sealed_handoff_verifier_transfer_proof_bound",
        "sealed_handoff_verifier_transfer_blocks_verifier_invocation",
        "previous_closeouts_carried_forward",
        "target_migration_hash_locked",
        "rollback_and_post_apply_verifier_bound",
        "archive_retention_sealed_handoff_contract_blocks_handoff_verifier_execution_and_database_apply",
        "preview_has_no_side_effects_no_handoff_no_verifier_no_receipt_no_execution_no_signing",
    ]
    abort_conditions = [
        "abort_if_archive_retention_sealed_handoff_proof_not_ready",
        "abort_if_sealed_handoff_proof_missing",
        "abort_if_sealed_handoff_manifest_hash_missing_or_mismatched",
        "abort_if_verifier_transfer_allows_invocation_or_receipt_persistence",
        "abort_if_previous_closeout_ids_do_not_match",
        "abort_if_target_migration_hash_is_not_locked",
        "abort_if_rollback_or_post_apply_verifier_binding_missing",
        "abort_if_any_secret_or_signature_material_is_included",
        "abort_if_any_endpoint_sql_database_runner_verifier_or_executor_action_is_allowed",
        "abort_if_manual_review_mode_is_not_exception_only",
    ]
    previous_ready = (
        transfer_result.get("result")
        == "DB_APPLY_CONTROLLED_DRY_RUN_RETENTION_BOUNDARY_NO_WRITE_ARCHIVE_PROOF_CLOSEOUT_READY"
        and future_handoff.get(
            "ready_for_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        )
        is True
    )
    handoff_ready = (
        handoff_proof.get("handoff_status")
        == "archive_retention_sealed_handoff_proof_preview_ready"
        and handoff_proof.get("handoff_mode")
        == "archive_retention_sealed_handoff_proof_preview_only"
        and handoff_proof.get("archive_retention_sealed_handoff_proof_field_count")
        == 12
    )
    handoff_manifest = handoff_proof.get("sealed_handoff_manifest") or {}
    expected_handoff_manifest_hash = hashlib.sha256(
        json.dumps(handoff_manifest, sort_keys=True).encode("utf-8")
    ).hexdigest()
    sealed_handoff_manifest_hash_locked = (
        bool(handoff_manifest)
        and len(handoff_proof.get("sealed_handoff_manifest_hash") or "") == 64
        and handoff_proof.get("sealed_handoff_manifest_hash")
        == expected_handoff_manifest_hash
    )
    target_hash_locked = (
        bool(handoff_closeout.get("target_file"))
        and bool(handoff_closeout.get("expected_sha256"))
        and bool(handoff_closeout.get("actual_sha256"))
        and handoff_closeout.get("expected_sha256")
        == handoff_closeout.get("actual_sha256")
        and handoff_closeout.get("hash_matches") is True
    )
    rollback_and_verifier_bound = bool(
        rollback_binding.get("rollback_binding_id")
    ) and bool(verifier_binding.get("post_apply_verifier_binding_id"))
    previous_closeouts_carried_forward = (
        handoff_closeout.get("retention_boundary_no_write_archive_proof_closeout_only")
        is True
        and handoff_closeout.get("archive_retention_sealed_handoff_proof_only")
        is True
        and handoff_proof.get("source_no_write_ledger_retention_proof_closeout_id")
        == source_retention_closeout_id
        and handoff_proof.get("source_retention_boundary_no_write_archive_proof_id")
        == source_archive_id
        and archive_proof.get("archive_proof_id") == source_archive_id
    )
    source_contract_blocks_handoff_verifier_execution_and_apply = (
        handoff_contract.get(
            "permits_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        )
        is True
        and handoff_contract.get("sealed_handoff_write_allowed") is False
        and handoff_contract.get("persists_verifier_receipt") is False
        and handoff_contract.get("verifier_invoked") is False
        and handoff_contract.get("executes_database_apply") is False
        and handoff_contract.get("database_apply_authorized") is False
        and handoff_contract.get("writes_database") is False
    )
    transfer_manifest = {
        "source_retention_boundary_no_write_archive_proof_closeout_id": (
            source_closeout_id
        ),
        "source_archive_retention_sealed_handoff_proof_id": source_handoff_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "sealed_handoff_manifest_hash": handoff_proof.get(
            "sealed_handoff_manifest_hash"
        ),
        "target_file": handoff_closeout.get("target_file"),
        "expected_sha256": handoff_closeout.get("expected_sha256"),
        "actual_sha256": handoff_closeout.get("actual_sha256"),
        "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
        "post_apply_verifier_binding_id": verifier_binding.get(
            "post_apply_verifier_binding_id"
        ),
        "verifier_transfer_mode": "sealed_handoff_verifier_transfer_proof_preview_only",
        "manual_review_mode": "exception_only",
    }
    verifier_transfer_manifest_hash = hashlib.sha256(
        json.dumps(transfer_manifest, sort_keys=True).encode("utf-8")
    ).hexdigest()
    transfer_bound = (
        previous_ready
        and handoff_ready
        and sealed_handoff_manifest_hash_locked
        and bool(source_closeout_id)
        and bool(source_handoff_id)
        and bool(source_archive_id)
        and len(transfer_fields) == 12
        and bool(verifier_transfer_manifest_hash)
    )
    verifier_transfer_blocks_invocation = True
    nonsecret_machine_readable_transfer = (
        transfer_bound
        and bool(verifier_transfer_manifest_hash)
        and transfer_manifest.get("manual_review_mode") == "exception_only"
    )
    side_effect_free = (
        int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_endpoint_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and int(summary.get("sealed_handoff_written_count") or 0) == 0
        and int(summary.get("retention_archive_written_count") or 0) == 0
        and int(summary.get("ledger_retention_written_count") or 0) == 0
        and int(summary.get("ledger_written_count") or 0) == 0
        and int(summary.get("receipt_persistence_storage_written_count") or 0) == 0
        and int(summary.get("persists_verifier_receipt_count") or 0) == 0
        and int(summary.get("verifier_invoked_count") or 0) == 0
        and int(summary.get("dry_run_executor_invoked_count") or 0) == 0
        and int(summary.get("runner_invocation_performed_count") or 0) == 0
        and int(summary.get("signs_database_apply_authorization_count") or 0) == 0
        and handoff_proof.get("sealed_handoff_written") is False
        and handoff_proof.get("verifier_invoked") is False
        and handoff_proof.get("database_written") is False
        and handoff_proof.get("database_apply_authorized") is False
        and safety.get("executes_endpoint") is False
        and safety.get("executes_sql") is False
        and safety.get("writes_database") is False
        and safety.get("executes_database_apply") is False
    )
    sealed_handoff_verifier_transfer_proof = {
        "sealed_handoff_verifier_transfer_proof_id": transfer_id,
        "authorization_material_type": (
            "controlled_dry_run_sealed_handoff_verifier_transfer_proof"
        ),
        "source_archive_retention_sealed_handoff_proof_closeout_id": closeout_id,
        "source_retention_boundary_no_write_archive_proof_closeout_id": (
            source_closeout_id
        ),
        "source_archive_retention_sealed_handoff_proof_id": source_handoff_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "source_no_write_ledger_retention_proof_closeout_id": (
            source_retention_closeout_id
        ),
        "required_command_shape_hash": handoff_proof.get(
            "required_command_shape_hash"
        ),
        "target_file": handoff_closeout.get("target_file"),
        "expected_sha256": handoff_closeout.get("expected_sha256"),
        "actual_sha256": handoff_closeout.get("actual_sha256"),
        "hash_matches": handoff_closeout.get("hash_matches"),
        "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
        "post_apply_verifier_binding_id": verifier_binding.get(
            "post_apply_verifier_binding_id"
        ),
        "sealed_handoff_manifest_hash": handoff_proof.get(
            "sealed_handoff_manifest_hash"
        ),
        "verifier_transfer_manifest": transfer_manifest,
        "verifier_transfer_manifest_hash": verifier_transfer_manifest_hash,
        "verifier_transfer_status": (
            "sealed_handoff_verifier_transfer_proof_preview_ready"
        ),
        "verifier_transfer_mode": (
            "sealed_handoff_verifier_transfer_proof_preview_only"
        ),
        "sealed_handoff_verifier_transfer_proof_fields": transfer_fields,
        "sealed_handoff_verifier_transfer_proof_field_count": len(
            transfer_fields
        ),
        "verifier_transfer_write_locked": True,
        "verifier_transfer_write_allowed": False,
        "verifier_transfer_written": False,
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_verifier_transfer_write_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    checks = [
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "retention_boundary_no_write_archive_proof_closeout_ready",
            previous_ready,
            {
                "result": transfer_result.get("result"),
                "ready_count": summary.get(
                    "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_ready_count"
                ),
            },
            "wait_for_retention_boundary_no_write_archive_proof_closeout",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "archive_retention_sealed_handoff_proof_ready",
            handoff_ready,
            {
                "handoff_status": handoff_proof.get("handoff_status"),
                "handoff_mode": handoff_proof.get("handoff_mode"),
                "field_count": handoff_proof.get(
                    "archive_retention_sealed_handoff_proof_field_count"
                ),
            },
            "wait_for_archive_retention_sealed_handoff_proof",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "sealed_handoff_manifest_hash_locked",
            sealed_handoff_manifest_hash_locked,
            {
                "manifest_hash_present": bool(
                    handoff_proof.get("sealed_handoff_manifest_hash")
                ),
                "expected_hash_matches": sealed_handoff_manifest_hash_locked,
            },
            "wait_for_sealed_handoff_manifest_hash_lock",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "sealed_handoff_verifier_transfer_proof_bound",
            transfer_bound,
            {
                "transfer_id": transfer_id,
                "source_handoff_id": source_handoff_id,
                "source_closeout_id": source_closeout_id,
                "field_count": len(transfer_fields),
            },
            "wait_for_sealed_handoff_verifier_transfer_proof",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "sealed_handoff_verifier_transfer_blocks_verifier_invocation",
            verifier_transfer_blocks_invocation,
            {
                "verifier_invocation_allowed": False,
                "verifier_invoked": False,
                "persists_verifier_receipt": False,
            },
            "abort_if_verifier_transfer_allows_invocation_or_receipt_persistence",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "previous_closeouts_carried_forward",
            previous_closeouts_carried_forward,
            {
                "source_handoff_only": handoff_closeout.get(
                    "archive_retention_sealed_handoff_proof_only"
                ),
                "source_closeout_only": handoff_closeout.get(
                    "retention_boundary_no_write_archive_proof_closeout_only"
                ),
                "source_archive_closeout_id": source_archive_closeout.get(
                    "no_write_ledger_retention_proof_closeout_id"
                ),
            },
            "wait_for_previous_closeout_chain",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "target_migration_hash_locked",
            target_hash_locked,
            {
                "target_file": handoff_closeout.get("target_file"),
                "hash_matches": handoff_closeout.get("hash_matches"),
                "expected_sha256_present": bool(
                    handoff_closeout.get("expected_sha256")
                ),
                "actual_sha256_present": bool(handoff_closeout.get("actual_sha256")),
            },
            "wait_for_target_migration_hash_lock",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "rollback_and_post_apply_verifier_bound",
            rollback_and_verifier_bound,
            {
                "rollback_binding_id": rollback_binding.get("rollback_binding_id"),
                "post_apply_verifier_binding_id": verifier_binding.get(
                    "post_apply_verifier_binding_id"
                ),
            },
            "wait_for_rollback_and_post_apply_verifier_bindings",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "archive_retention_sealed_handoff_contract_blocks_handoff_verifier_execution_and_database_apply",
            source_contract_blocks_handoff_verifier_execution_and_apply,
            {
                "permits_future_handoff_proof": handoff_contract.get(
                    "permits_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
                ),
                "sealed_handoff_write_allowed": handoff_contract.get(
                    "sealed_handoff_write_allowed"
                ),
                "verifier_invoked": handoff_contract.get("verifier_invoked"),
                "database_apply_authorized": handoff_contract.get(
                    "database_apply_authorized"
                ),
            },
            "abort_if_source_contract_allows_handoff_verifier_execution_or_database_apply",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "sealed_handoff_verifier_transfer_has_nonsecret_machine_readable_manifest",
            nonsecret_machine_readable_transfer,
            {
                "manifest_hash_present": bool(verifier_transfer_manifest_hash),
                "accepts_plaintext_secret": sealed_handoff_verifier_transfer_proof.get(
                    "accepts_plaintext_secret"
                ),
                "secret_material_included": sealed_handoff_verifier_transfer_proof.get(
                    "secret_material_included"
                ),
                "signature_material_included": sealed_handoff_verifier_transfer_proof.get(
                    "signature_material_included"
                ),
            },
            "abort_if_verifier_transfer_manifest_contains_secret_signature_or_is_not_machine_readable",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "preview_has_no_side_effects_no_handoff_no_verifier_no_receipt_no_execution_no_signing",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_endpoint_count": summary.get("executes_endpoint_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
                "verifier_invoked_count": summary.get("verifier_invoked_count", 0),
            },
            "abort_on_preview_handoff_verifier_receipt_execution_or_signing_side_effect",
        ),
        _controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check(
            "manual_review_not_required_for_safe_preview",
            handoff_contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only",
            {
                "contract_manual_review_mode": handoff_contract.get(
                    "manual_review_mode"
                ),
                "safety_manual_review_mode": safety.get("manual_review_mode"),
            },
            "keep_manual_review_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_CONTROLLED_DRY_RUN_ARCHIVE_RETENTION_SEALED_HANDOFF_PROOF_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RETENTION_BOUNDARY_NO_WRITE_ARCHIVE_PROOF_CLOSEOUT"
    )
    future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof = {
        "archive_retention_sealed_handoff_proof_closeout_id": closeout_id,
        "sealed_handoff_verifier_transfer_proof_id": transfer_id,
        "source_retention_boundary_no_write_archive_proof_closeout_id": (
            source_closeout_id
        ),
        "source_archive_retention_sealed_handoff_proof_id": source_handoff_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof": (
            closeout_ready
        ),
        "can_enter_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof_closeout": (
            closeout_ready
        ),
        "archive_retention_sealed_handoff_proof_closeout_ready": closeout_ready,
        "retention_boundary_no_write_archive_proof_closeout_ready": previous_ready,
        "archive_retention_sealed_handoff_proof_ready": handoff_ready,
        "sealed_handoff_manifest_hash_locked": sealed_handoff_manifest_hash_locked,
        "sealed_handoff_verifier_transfer_proof_bound": closeout_ready,
        "verifier_transfer_write_locked": True,
        "verifier_transfer_write_allowed": False,
        "verifier_transfer_written": False,
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_verifier_transfer_write_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "writes_database": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
        "waiting_checks": waiting_checks,
        "manual_review_mode": "exception_only",
    }
    archive_retention_sealed_handoff_proof_closeout = {
        "archive_retention_sealed_handoff_proof_closeout_id": closeout_id,
        "authorization_material_type": (
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
        ),
        "source_retention_boundary_no_write_archive_proof_closeout_id": (
            source_closeout_id
        ),
        "source_archive_retention_sealed_handoff_proof_id": source_handoff_id,
        "source_retention_boundary_no_write_archive_proof_id": source_archive_id,
        "source_no_write_ledger_retention_proof_closeout_id": (
            source_retention_closeout_id
        ),
        "required_command_shape_hash": handoff_proof.get(
            "required_command_shape_hash"
        ),
        "status": closeout_status,
        "ready_for_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof": (
            closeout_ready
        ),
        "archive_retention_sealed_handoff_proof_closeout_fields": (
            closeout_fields
        ),
        "archive_retention_sealed_handoff_proof_closeout_field_count": len(
            closeout_fields
        ),
        "archive_retention_sealed_handoff_proof_closeout_acceptance_gates": (
            acceptance_gates
        ),
        "archive_retention_sealed_handoff_proof_closeout_acceptance_gate_count": len(
            acceptance_gates
        ),
        "sealed_handoff_verifier_transfer_proof": (
            sealed_handoff_verifier_transfer_proof
        ),
        "sealed_handoff_verifier_transfer_proof_count": 1,
        "sealed_handoff_verifier_transfer_proof_field_count": len(
            transfer_fields
        ),
        "archive_retention_sealed_handoff_proof": handoff_proof,
        "archive_retention_sealed_handoff_proof_count": 1,
        "retention_boundary_no_write_archive_proof_closeout": handoff_closeout,
        "retention_boundary_no_write_archive_proof_closeout_count": 1,
        "target_file": handoff_closeout.get("target_file"),
        "expected_sha256": handoff_closeout.get("expected_sha256"),
        "actual_sha256": handoff_closeout.get("actual_sha256"),
        "hash_matches": handoff_closeout.get("hash_matches"),
        "target_migration_hash_locked": target_hash_locked,
        "rollback_binding": rollback_binding,
        "rollback_binding_count": 1,
        "post_apply_verifier_binding": verifier_binding,
        "post_apply_verifier_binding_count": 1,
        "abort_conditions": abort_conditions,
        "abort_condition_count": len(abort_conditions),
        "dry_run_only": True,
        "check_mode_only": True,
        "archive_retention_sealed_handoff_proof_closeout_only": True,
        "sealed_handoff_verifier_transfer_proof_only": True,
        "requires_fresh_production_truth_in_same_run": True,
        "requires_post_apply_verifier": True,
        "verifier_transfer_write_locked": True,
        "verifier_transfer_write_allowed": False,
        "verifier_transfer_written": False,
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "dry_run_executor_invoked": False,
        "runner_invocation_performed": False,
        "endpoint_executed": False,
        "sql_executed": False,
        "database_written": False,
        "execution_receipt_present": False,
        "runner_execution_authorized": False,
        "dry_run_execution_authorized": False,
        "execution_authorized": False,
        "endpoint_execution_allowed": False,
        "sql_execution_allowed": False,
        "database_write_allowed": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_verifier_transfer_write_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "database_apply_authorized": False,
        "issues_database_apply_authorization": False,
        "signs_database_apply_authorization": False,
        "accepts_plaintext_secret": False,
        "reads_secret_in_preview": False,
        "signature_material_included": False,
        "secret_material_included": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "captures_stdout": False,
        "captures_stderr": False,
        "stdout_included": False,
        "stderr_included": False,
    }
    archive_retention_sealed_handoff_proof_closeout_contract = {
        "mode": "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_and_sealed_handoff_verifier_transfer_proof_only",
        "source_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-archive-retention-sealed-handoff-proof-closeout"
        ),
        "source_retention_boundary_no_write_archive_proof_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/"
            "auto-policy-db-apply-controlled-dry-run-retention-boundary-no-write-archive-proof-closeout"
        ),
        "machine_verifiable": True,
        "permits_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof": (
            closeout_ready
        ),
        "verifier_transfer_write_locked": True,
        "verifier_transfer_write_allowed": False,
        "verifier_transfer_written": False,
        "sealed_handoff_write_locked": True,
        "sealed_handoff_write_allowed": False,
        "sealed_handoff_written": False,
        "verifier_receipt_persistence_locked": True,
        "verifier_receipt_persistence_allowed": False,
        "verifier_receipt_persisted": False,
        "persists_verifier_receipt": False,
        "verifier_invocation_locked": True,
        "verifier_invocation_allowed": False,
        "verifier_invoked": False,
        "verifier_receipt_present": False,
        "ready_for_database_apply_now": False,
        "ready_for_archive_retention_sealed_handoff_write_now": False,
        "ready_for_verifier_transfer_write_now": False,
        "ready_for_verifier_receipt_persistence_now": False,
        "ready_for_verifier_invocation_now": False,
        "ready_for_dry_run_executor_invocation_now": False,
        "ready_for_actual_dry_run_execution_now": False,
        "accepts_plaintext_secret": False,
        "performs_detached_signature_verification": False,
        "executes_authorization_evidence": False,
        "executes_database_apply": False,
        "executes_endpoint": False,
        "executes_sql": False,
        "issues_database_apply_authorization": False,
        "database_apply_authorized": False,
        "signs_database_apply_authorization": False,
        "writes_database": False,
        "executes_in_preview": False,
        "secret_material_required_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    output_summary = dict(summary)
    output_summary.update(
        {
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_ready_count": (
                1 if closeout_ready else 0
            ),
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check_count": len(
                checks
            ),
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_pass_count": (
                passed_count
            ),
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_waiting_count": len(
                waiting_checks
            ),
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_count": 1,
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_field_count": len(
                closeout_fields
            ),
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_acceptance_gate_count": len(
                acceptance_gates
            ),
            "sealed_handoff_verifier_transfer_proof_count": 1,
            "sealed_handoff_verifier_transfer_proof_field_count": len(
                transfer_fields
            ),
            "sealed_handoff_manifest_hash_locked_count": (
                1 if sealed_handoff_manifest_hash_locked else 0
            ),
            "verifier_transfer_write_locked_count": 1,
            "verifier_transfer_write_allowed_count": 0,
            "verifier_transfer_written_count": 0,
            "sealed_handoff_write_allowed_count": 0,
            "sealed_handoff_written_count": 0,
            "persists_verifier_receipt_count": 0,
            "verifier_invoked_count": 0,
            "verifier_receipt_present_count": 0,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "dry_run_executor_invoked_count": 0,
            "runner_invocation_performed_count": 0,
            "endpoint_executed_count": 0,
            "sql_executed_count": 0,
            "database_written_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: (
                summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0) or 0
            ),
        }
    )
    return {
        "policy": AUTO_POLICY_DB_APPLY_CONTROLLED_DRY_RUN_ARCHIVE_RETENTION_SEALED_HANDOFF_PROOF_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(transfer_result.get("success")),
        "generated_at": transfer_result.get("generated_at"),
        "source_policy": transfer_result.get("policy"),
        "stats": transfer_result.get("stats") or {},
        "summary": output_summary,
        "future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof": (
            future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof
        ),
        "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout": (
            archive_retention_sealed_handoff_proof_closeout
        ),
        "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_contract": (
            archive_retention_sealed_handoff_proof_closeout_contract
        ),
        "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_checks": (
            checks
        ),
        "source_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_summary": (
            summary
        ),
        "source_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract": (
            handoff_contract
        ),
        "source_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout": (
            handoff_closeout
        ),
        "source_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof": (
            future_handoff
        ),
        "safety": {
            "read_only_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "signs_database_apply_authorization": False,
            "performs_detached_signature_verification": False,
            "persists_verifier_receipt": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout to build a future sealed handoff verifier transfer proof closeout.",
            "Keep verifier invocation and verifier receipt persistence disabled until a later verifier transfer closeout proves the transfer boundary.",
            "This closeout still does not authorize endpoint execution, SQL, DB writes, handoff writes, verifier invocation, verifier receipt persistence, receipt storage, or database apply.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_lane_guard(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Guard the future DB apply authorization lane without issuing authorization."""
    closeout = build_pchome_auto_policy_db_apply_authorization_request_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    package = closeout.get("final_exact_request_package") or {}
    manifest = closeout.get("machine_request_manifest") or {}
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    template = package.get("exact_request_payload_template") or {}
    manifest_steps = manifest.get("manifest_steps") or []
    side_effect_free = (
        int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and package.get("reads_secret_in_preview") is False
        and package.get("executes_shell_in_preview") is False
        and package.get("executes_sql_in_preview") is False
        and package.get("writes_database_in_preview") is False
        and safety.get("writes_database") is False
    )
    template_has_truth_gate = (
        isinstance(template.get("fresh_production_truth"), dict)
        and template["fresh_production_truth"].get("same_run_only") is True
        and template["fresh_production_truth"].get("required") is True
    )
    manifest_step_names = {step.get("name") for step in manifest_steps}
    checks = [
        _authorization_lane_guard_check(
            "request_closeout_ready",
            closeout.get("result") == "DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT_READY"
            and package.get("ready_for_exact_authorization_request_package") is True,
            {
                "result": closeout.get("result"),
                "ready_for_exact_authorization_request_package": package.get(
                    "ready_for_exact_authorization_request_package"
                ),
            },
            "wait_for_authorization_request_closeout",
        ),
        _authorization_lane_guard_check(
            "package_does_not_issue_apply_authorization",
            package.get("issues_database_apply_authorization") is False
            and package.get("ready_for_database_apply_now") is False,
            {
                "issues_database_apply_authorization": package.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": package.get("ready_for_database_apply_now"),
            },
            "block_if_package_issues_apply_authorization",
        ),
        _authorization_lane_guard_check(
            "manifest_does_not_issue_apply_authorization",
            manifest.get("issues_database_apply_authorization") is False
            and manifest.get("writes_database") is False
            and manifest.get("executes_in_preview") is False,
            {
                "issues_database_apply_authorization": manifest.get(
                    "issues_database_apply_authorization"
                ),
                "writes_database": manifest.get("writes_database"),
                "executes_in_preview": manifest.get("executes_in_preview"),
            },
            "block_if_manifest_executes_or_authorizes",
        ),
        _authorization_lane_guard_check(
            "fresh_production_truth_same_run_required",
            template_has_truth_gate,
            {"fresh_production_truth": template.get("fresh_production_truth")},
            "require_same_run_production_truth",
        ),
        _authorization_lane_guard_check(
            "exact_request_payload_complete",
            int(summary.get("exact_request_payload_field_count") or 0) == 10
            and package.get("payload_template_field_count") == 10,
            {
                "exact_request_payload_field_count": summary.get(
                    "exact_request_payload_field_count", 0
                ),
                "payload_template_field_count": package.get("payload_template_field_count"),
            },
            "wait_for_exact_request_payload",
        ),
        _authorization_lane_guard_check(
            "machine_manifest_complete",
            int(summary.get("machine_request_manifest_step_count") or 0) == 6
            and manifest.get("manifest_step_count") == 6,
            {
                "machine_request_manifest_step_count": summary.get(
                    "machine_request_manifest_step_count", 0
                ),
                "manifest_step_count": manifest.get("manifest_step_count"),
            },
            "wait_for_machine_request_manifest",
        ),
        _authorization_lane_guard_check(
            "secret_rejection_step_present",
            "reject_secret_material" in manifest_step_names
            and template.get("operator_acknowledges_secret_boundary") is True,
            {
                "manifest_step_names": sorted(name for name in manifest_step_names if name),
                "operator_acknowledges_secret_boundary": template.get(
                    "operator_acknowledges_secret_boundary"
                ),
            },
            "block_until_secret_rejection_step_exists",
        ),
        _authorization_lane_guard_check(
            "rollback_acknowledgement_present",
            template.get("operator_acknowledges_rollback_boundary") is True,
            {
                "operator_acknowledges_rollback_boundary": template.get(
                    "operator_acknowledges_rollback_boundary"
                ),
            },
            "block_until_rollback_boundary_acknowledged",
        ),
        _authorization_lane_guard_check(
            "migration_hash_locked",
            bool(package.get("target_file"))
            and bool(package.get("expected_sha256"))
            and package.get("hash_matches") is True,
            {
                "target_file": package.get("target_file"),
                "hash_matches": package.get("hash_matches"),
            },
            "abort_on_migration_hash_gap",
        ),
        _authorization_lane_guard_check(
            "preview_has_no_side_effects",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
            },
            "abort_on_preview_side_effect",
        ),
        _authorization_lane_guard_check(
            "source_intake_and_closeout_ids_present",
            bool(package.get("source_intake_id"))
            and bool(package.get("source_closeout_boundary_id"))
            and bool(package.get("source_dry_run_shell_preview_id")),
            {
                "source_intake_id": package.get("source_intake_id"),
                "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
                "source_dry_run_shell_preview_id": package.get("source_dry_run_shell_preview_id"),
            },
            "wait_for_source_proof_ids",
        ),
        _authorization_lane_guard_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0,
            {LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0)},
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    lane_ready = not waiting_checks
    lane_status = (
        "DB_APPLY_AUTHORIZATION_LANE_GUARD_READY"
        if lane_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT"
    )
    lane_entry_requirements = [
        {
            "key": "production_truth_refreshed_in_same_run",
            "required": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "exact_request_payload_matches_template",
            "required": True,
            "field_count": len(template),
        },
        {
            "key": "migration_file_hash_matches_package",
            "required": True,
            "target_file": package.get("target_file"),
            "expected_sha256": package.get("expected_sha256"),
        },
        {
            "key": "secret_material_absent_from_request",
            "required": True,
            "rejects_database_url": True,
            "rejects_authorization_header": True,
            "rejects_cookie": True,
        },
        {
            "key": "rollback_boundary_acknowledged",
            "required": True,
        },
        {
            "key": "direct_apply_rejected_until_next_lane",
            "required": True,
            "issues_database_apply_authorization": False,
        },
    ]
    lane_transfer_contract = {
        "mode": "future_authorization_lane_entry_guard_only",
        "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-lane-guard",
        "source_request_closeout_endpoint": (
            "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-closeout"
        ),
        "entry_requirement_count": len(lane_entry_requirements),
        "machine_verifiable": True,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "executes_in_preview": False,
        "writes_database": False,
    }
    future_authorization_lane_guard = {
        "guard_id": _db_apply_authorization_lane_guard_id(closeout),
        "source_closeout_package_id": package.get("package_id"),
        "source_intake_id": package.get("source_intake_id"),
        "source_closeout_boundary_id": package.get("source_closeout_boundary_id"),
        "source_dry_run_shell_preview_id": package.get("source_dry_run_shell_preview_id"),
        "status": lane_status,
        "ready_for_future_authorization_lane_entry": lane_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "request_scope": "future_explicit_db_apply_authorization_only",
        "target_file": package.get("target_file"),
        "expected_sha256": package.get("expected_sha256"),
        "actual_sha256": package.get("actual_sha256"),
        "hash_matches": package.get("hash_matches"),
        "requires_fresh_production_truth_in_same_run": True,
        "operator_secret_boundary": "future_shell_only",
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_LANE_GUARD_POLICY,
        "result": lane_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_lane_guard_ready_count": 1 if lane_ready else 0,
            "lane_guard_check_count": len(checks),
            "lane_guard_pass_count": passed_count,
            "lane_guard_waiting_count": len(waiting_checks),
            "authorization_request_closeout_ready_count": summary.get(
                "authorization_request_closeout_ready_count", 0
            ),
            "exact_request_payload_field_count": summary.get(
                "exact_request_payload_field_count", 0
            ),
            "machine_request_manifest_step_count": summary.get(
                "machine_request_manifest_step_count", 0
            ),
            "lane_entry_requirement_count": len(lane_entry_requirements),
            "required_request_evidence_count": summary.get("required_request_evidence_count", 0),
            "authorization_acceptance_gate_count": summary.get(
                "authorization_acceptance_gate_count", 0
            ),
            "rejection_reason_count": summary.get("rejection_reason_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "future_authorization_lane_guard": future_authorization_lane_guard,
        "lane_transfer_contract": lane_transfer_contract,
        "lane_entry_requirements": lane_entry_requirements,
        "lane_guard_checks": checks,
        "source_request_closeout_summary": summary,
        "source_final_exact_request_package": package,
        "source_machine_request_manifest": manifest,
        "safety": {
            "read_only_db_apply_authorization_lane_guard": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this guard to decide whether the exact request package can enter a future authorization lane.",
            "Keep DB apply authorization, shell execution, SQL execution, and database writes blocked in this guard.",
            "Require fresh production truth in the future authorization lane before any apply decision is issued.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_request_closeout(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Close out authorization request intake into a final exact request package."""
    intake = build_pchome_auto_policy_db_apply_authorization_request_intake(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    request_intake = intake.get("authorization_request_intake") or {}
    envelope = intake.get("authorization_envelope") or {}
    summary = intake.get("summary") or {}
    schema = intake.get("request_payload_schema") or {}
    acceptance_gates = intake.get("authorization_acceptance_gates") or []
    evidence = intake.get("required_request_evidence") or []
    rejection_reasons = intake.get("rejection_reasons") or []
    required_fields = schema.get("required_fields") or []
    side_effect_free = (
        int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and request_intake.get("reads_secret_in_preview") is False
        and request_intake.get("executes_shell_in_preview") is False
        and request_intake.get("executes_sql_in_preview") is False
        and request_intake.get("writes_database_in_preview") is False
    )
    checks = [
        _authorization_request_closeout_check(
            "authorization_request_intake_ready",
            intake.get("result") == "DB_APPLY_AUTHORIZATION_REQUEST_INTAKE_READY"
            and request_intake.get("ready_for_authorization_request_intake") is True,
            {
                "result": intake.get("result"),
                "ready_for_authorization_request_intake": request_intake.get(
                    "ready_for_authorization_request_intake"
                ),
            },
            "wait_for_authorization_request_intake",
        ),
        _authorization_request_closeout_check(
            "source_closeout_ready",
            int(summary.get("closeout_ready_count") or 0) == 1,
            {"closeout_ready_count": summary.get("closeout_ready_count", 0)},
            "wait_for_controlled_dry_run_shell_closeout",
        ),
        _authorization_request_closeout_check(
            "required_request_evidence_complete",
            len(evidence) == 7 and int(summary.get("required_request_evidence_count") or 0) == 7,
            {"required_request_evidence_count": summary.get("required_request_evidence_count", 0)},
            "wait_for_required_request_evidence",
        ),
        _authorization_request_closeout_check(
            "request_schema_complete",
            len(required_fields) == 10
            and int(summary.get("request_payload_required_field_count") or 0) == 10,
            {"required_fields": required_fields},
            "wait_for_request_payload_schema",
        ),
        _authorization_request_closeout_check(
            "acceptance_gates_all_passed",
            len(acceptance_gates) == 11
            and int(summary.get("authorization_acceptance_waiting_count", 0) or 0) == 0,
            {
                "authorization_acceptance_gate_count": summary.get(
                    "authorization_acceptance_gate_count", 0
                ),
                "authorization_acceptance_waiting_count": summary.get(
                    "authorization_acceptance_waiting_count", 0
                ),
            },
            "route_failed_acceptance_gate_to_exception_review",
        ),
        _authorization_request_closeout_check(
            "rejection_policy_complete",
            len(rejection_reasons) == 10 and "direct_database_apply_requested_from_intake" in rejection_reasons,
            {"rejection_reason_count": len(rejection_reasons)},
            "wait_for_rejection_policy",
        ),
        _authorization_request_closeout_check(
            "envelope_accepts_request_but_not_apply",
            envelope.get("accepts_authorization_request") is True
            and envelope.get("issues_database_apply_authorization") is False
            and envelope.get("ready_for_database_apply_now") is False,
            {
                "accepts_authorization_request": envelope.get("accepts_authorization_request"),
                "issues_database_apply_authorization": envelope.get(
                    "issues_database_apply_authorization"
                ),
                "ready_for_database_apply_now": envelope.get("ready_for_database_apply_now"),
            },
            "block_if_intake_issues_apply_authorization",
        ),
        _authorization_request_closeout_check(
            "migration_target_and_hash_locked",
            bool(request_intake.get("target_file"))
            and bool(request_intake.get("expected_sha256"))
            and request_intake.get("hash_matches") is True,
            {
                "target_file": request_intake.get("target_file"),
                "hash_matches": request_intake.get("hash_matches"),
            },
            "abort_on_target_or_hash_gap",
        ),
        _authorization_request_closeout_check(
            "secret_boundary_future_shell_only",
            request_intake.get("operator_secret_boundary") == "future_shell_only"
            and request_intake.get("reads_secret_in_preview") is False,
            {
                "operator_secret_boundary": request_intake.get("operator_secret_boundary"),
                "reads_secret_in_preview": request_intake.get("reads_secret_in_preview"),
            },
            "abort_on_secret_boundary_violation",
        ),
        _authorization_request_closeout_check(
            "preview_has_no_shell_sql_or_db_side_effect",
            side_effect_free,
            {
                "reads_secret_count": summary.get("reads_secret_count", 0),
                "executes_script_count": summary.get("executes_script_count", 0),
                "executes_sql_count": summary.get("executes_sql_count", 0),
                "writes_database_count": summary.get("writes_database_count", 0),
            },
            "abort_on_preview_side_effect",
        ),
        _authorization_request_closeout_check(
            "direct_apply_rejected",
            envelope.get("rejects_direct_database_apply") is True,
            {"rejects_direct_database_apply": envelope.get("rejects_direct_database_apply")},
            "reject_direct_database_apply_request",
        ),
        _authorization_request_closeout_check(
            "manual_review_regression_absent",
            int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0) == 0,
            {LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0)},
            "route_failed_verifier_to_exception_only",
        ),
    ]
    passed_count = sum(1 for check in checks if check.get("passed"))
    waiting_checks = [check for check in checks if not check.get("passed")]
    closeout_ready = not waiting_checks
    closeout_status = (
        "DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT_READY"
        if closeout_ready
        else "WAITING_FOR_DB_APPLY_AUTHORIZATION_REQUEST_INTAKE"
    )
    exact_request_payload_template = {
        "requester": "{future_automation_or_operator_identity}",
        "requested_at": "{utc_iso8601}",
        "reason": "apply additive PChome auto-policy evidence receipts migration",
        "target_file": request_intake.get("target_file"),
        "expected_sha256": request_intake.get("expected_sha256"),
        "closeout_boundary_id": request_intake.get("source_closeout_boundary_id"),
        "dry_run_shell_preview_id": request_intake.get("source_dry_run_shell_preview_id"),
        "fresh_production_truth": {
            "required": True,
            "same_run_only": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        "operator_acknowledges_secret_boundary": True,
        "operator_acknowledges_rollback_boundary": True,
    }
    machine_request_manifest_steps = [
        {
            "name": "refresh_production_truth_in_same_run",
            "source_command": "python scripts/ops/check_production_version_truth.py",
            "executes_in_preview": False,
        },
        {
            "name": "refresh_authorization_request_closeout",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-closeout",
            "executes_in_preview": False,
        },
        {
            "name": "fill_exact_request_payload",
            "required_fields": required_fields,
            "writes_artifact_in_preview": False,
        },
        {
            "name": "reject_secret_material",
            "rejects_database_url": True,
            "rejects_authorization_header": True,
            "rejects_cookie": True,
        },
        {
            "name": "run_acceptance_gates",
            "gate_count": len(acceptance_gates),
            "executes_sql_in_preview": False,
        },
        {
            "name": "emit_request_to_future_apply_authorization_lane",
            "issues_database_apply_authorization": False,
            "writes_database": False,
        },
    ]
    final_exact_request_package = {
        "package_id": _db_apply_authorization_request_closeout_id(intake),
        "source_intake_id": request_intake.get("intake_id"),
        "source_closeout_boundary_id": request_intake.get("source_closeout_boundary_id"),
        "source_dry_run_shell_preview_id": request_intake.get("source_dry_run_shell_preview_id"),
        "status": closeout_status,
        "ready_for_exact_authorization_request_package": closeout_ready,
        "ready_for_database_apply_now": False,
        "issues_database_apply_authorization": False,
        "request_scope": "future_explicit_db_apply_authorization_only",
        "target_file": request_intake.get("target_file"),
        "expected_sha256": request_intake.get("expected_sha256"),
        "actual_sha256": request_intake.get("actual_sha256"),
        "hash_matches": request_intake.get("hash_matches"),
        "exact_request_payload_template": exact_request_payload_template,
        "payload_template_field_count": len(exact_request_payload_template),
        "operator_secret_boundary": "future_shell_only",
        "reads_secret_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "manual_review_mode": "exception_only",
    }

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT_POLICY,
        "result": closeout_status,
        "success": bool(intake.get("success")),
        "generated_at": intake.get("generated_at"),
        "source_policy": intake.get("policy"),
        "stats": intake.get("stats") or {},
        "summary": {
            "authorization_request_closeout_ready_count": 1 if closeout_ready else 0,
            "closeout_check_count": len(checks),
            "closeout_pass_count": passed_count,
            "closeout_waiting_count": len(waiting_checks),
            "authorization_request_intake_ready_count": summary.get(
                "authorization_request_intake_ready_count", 0
            ),
            "required_request_evidence_count": len(evidence),
            "request_payload_required_field_count": len(required_fields),
            "authorization_acceptance_gate_count": len(acceptance_gates),
            "rejection_reason_count": len(rejection_reasons),
            "exact_request_payload_field_count": len(exact_request_payload_template),
            "machine_request_manifest_step_count": len(machine_request_manifest_steps),
            "closeout_ready_count": summary.get("closeout_ready_count", 0),
            "future_apply_boundary_count": summary.get("future_apply_boundary_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "authorization_request_closeout": {
            "status": closeout_status,
            "ready_for_exact_authorization_request_package": closeout_ready,
            "ready_for_database_apply_now": False,
            "waiting_checks": waiting_checks,
            "manual_review_mode": "exception_only",
        },
        "final_exact_request_package": final_exact_request_package,
        "machine_request_manifest": {
            "mode": "future_apply_authorization_lane_only",
            "source_endpoint": "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-closeout",
            "manifest_steps": machine_request_manifest_steps,
            "manifest_step_count": len(machine_request_manifest_steps),
            "issues_database_apply_authorization": False,
            "executes_in_preview": False,
            "writes_database": False,
        },
        "closeout_checks": checks,
        "source_intake_summary": summary,
        "source_request_payload_schema": schema,
        "source_rejection_reasons": rejection_reasons,
        "safety": {
            "read_only_db_apply_authorization_request_closeout": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this closeout as the exact request payload template for the future apply authorization lane.",
            "Keep the future lane from issuing DB apply authorization unless fresh production truth is present in the same run.",
            "Reject direct apply, secrets, shell execution, SQL execution, or DB writes from this closeout.",
        ],
    }


def build_pchome_auto_policy_db_apply_authorization_request_intake(
    payload: dict[str, Any],
    batch_size: int = 12,
    *,
    execute_fetch: bool = False,
    timeout_seconds: int = PCHOME_FETCH_DEFAULT_TIMEOUT_SECONDS,
    http_get: Any = None,
) -> dict[str, Any]:
    """Build a no-write intake envelope for a future explicit DB apply authorization request."""
    closeout = build_pchome_auto_policy_db_apply_controlled_dry_run_shell_closeout(
        payload,
        batch_size=batch_size,
        execute_fetch=execute_fetch,
        timeout_seconds=timeout_seconds,
        http_get=http_get,
    )
    boundary = closeout.get("explicit_authorization_boundary") or {}
    summary = closeout.get("summary") or {}
    safety = closeout.get("safety") or {}
    closeout_ready = (
        closeout.get("result") == "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT_READY"
        and boundary.get("ready_for_explicit_apply_authorization_boundary") is True
    )
    side_effect_free = (
        int(summary.get("writes_script_count") or 0) == 0
        and int(summary.get("reads_secret_count") or 0) == 0
        and int(summary.get("executes_script_count") or 0) == 0
        and int(summary.get("executes_sql_count") or 0) == 0
        and int(summary.get("writes_database_count") or 0) == 0
        and boundary.get("reads_secret_in_preview") is False
        and boundary.get("executes_shell_in_preview") is False
        and boundary.get("executes_sql_in_preview") is False
        and boundary.get("writes_database_in_preview") is False
        and safety.get("writes_database") is False
    )
    target_file = boundary.get("target_file")
    expected_sha256 = boundary.get("expected_sha256")
    actual_sha256 = boundary.get("actual_sha256")
    hash_matches = boundary.get("hash_matches")
    intake_ready = closeout_ready and side_effect_free and bool(target_file) and hash_matches is True
    intake_status = (
        "DB_APPLY_AUTHORIZATION_REQUEST_INTAKE_READY"
        if intake_ready
        else "WAITING_FOR_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT"
    )
    required_request_evidence = [
        {
            "key": "fresh_production_truth_same_run",
            "required": True,
            "source_command": "python scripts/ops/check_production_version_truth.py",
        },
        {
            "key": "controlled_dry_run_shell_closeout_id",
            "required": True,
            "source_id": boundary.get("boundary_id"),
        },
        {
            "key": "final_handoff_package_id",
            "required": True,
            "source_id": boundary.get("source_final_handoff_package_id"),
        },
        {
            "key": "dry_run_shell_preview_id",
            "required": True,
            "source_id": boundary.get("source_dry_run_shell_preview_id"),
        },
        {
            "key": "migration_file_hash",
            "required": True,
            "target_file": target_file,
            "expected_sha256": expected_sha256,
            "actual_sha256": actual_sha256,
            "hash_matches": hash_matches,
        },
        {
            "key": "future_apply_boundaries",
            "required": True,
            "boundary_count": summary.get("future_apply_boundary_count", 0),
        },
        {
            "key": "no_secret_no_shell_no_sql_no_db_preview_counters",
            "required": True,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
        },
    ]
    request_payload_schema = {
        "required_fields": [
            "requester",
            "requested_at",
            "reason",
            "target_file",
            "expected_sha256",
            "closeout_boundary_id",
            "dry_run_shell_preview_id",
            "fresh_production_truth",
            "operator_acknowledges_secret_boundary",
            "operator_acknowledges_rollback_boundary",
        ],
        "optional_fields": [
            "change_window_utc",
            "rollback_contact",
            "ticket_url",
            "evidence_bundle_url",
        ],
        "rejects_extra_secret_material": True,
        "accepts_database_url": False,
        "accepts_authorization_header": False,
        "accepts_cookie": False,
    }
    authorization_acceptance_gates = [
        {
            "key": "closeout_result_ready",
            "passed": closeout.get("result") == "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT_READY",
            "failure_route": "refresh_controlled_dry_run_shell_closeout",
        },
        {
            "key": "explicit_boundary_ready",
            "passed": boundary.get("ready_for_explicit_apply_authorization_boundary") is True,
            "failure_route": "wait_for_explicit_authorization_boundary",
        },
        {
            "key": "closeout_checks_all_passed",
            "passed": int(summary.get("closeout_waiting_count") or 0) == 0
            and int(summary.get("closeout_pass_count") or 0) == int(summary.get("closeout_check_count") or -1),
            "failure_route": "route_failed_closeout_checks_to_exception_review",
        },
        {
            "key": "future_apply_boundaries_complete",
            "passed": int(summary.get("future_apply_boundary_count") or 0) >= 6,
            "failure_route": "wait_for_future_apply_boundaries",
        },
        {
            "key": "production_truth_refresh_required",
            "passed": boundary.get("requires_fresh_production_truth_in_future_run") is True,
            "failure_route": "abort_without_fresh_production_truth",
        },
        {
            "key": "target_file_present",
            "passed": bool(target_file),
            "failure_route": "wait_for_migration_file_target",
        },
        {
            "key": "migration_hash_present_and_matches",
            "passed": bool(expected_sha256) and bool(actual_sha256) and hash_matches is True,
            "failure_route": "abort_on_migration_hash_mismatch",
        },
        {
            "key": "final_handoff_source_present",
            "passed": bool(boundary.get("source_final_handoff_package_id")),
            "failure_route": "wait_for_final_handoff_package",
        },
        {
            "key": "shell_secret_boundary_clean",
            "passed": boundary.get("operator_secret_boundary") == "future_shell_only"
            and boundary.get("reads_secret_in_preview") is False,
            "failure_route": "abort_on_secret_boundary_violation",
        },
        {
            "key": "preview_has_no_side_effects",
            "passed": side_effect_free,
            "failure_route": "abort_on_preview_side_effect",
        },
        {
            "key": "explicit_request_payload_schema_defined",
            "passed": len(request_payload_schema["required_fields"]) == 10,
            "failure_route": "wait_for_request_schema",
        },
    ]
    rejection_reasons = [
        "production_truth_missing_or_stale",
        "controlled_dry_run_shell_closeout_not_ready",
        "closeout_boundary_id_missing",
        "migration_file_hash_missing_or_mismatch",
        "requester_missing",
        "reason_missing",
        "secret_material_in_request_payload",
        "preview_attempted_shell_sql_or_database_side_effect",
        "rollback_boundary_missing",
        "direct_database_apply_requested_from_intake",
    ]
    authorization_request_intake = {
        "intake_id": _db_apply_authorization_request_intake_id(closeout),
        "source_closeout_boundary_id": boundary.get("boundary_id"),
        "source_dry_run_shell_preview_id": boundary.get("source_dry_run_shell_preview_id"),
        "source_final_handoff_package_id": boundary.get("source_final_handoff_package_id"),
        "source_artifact_preview_id": boundary.get("source_artifact_preview_id"),
        "source_authorization_package_id": boundary.get("source_authorization_package_id"),
        "source_preflight_id": boundary.get("source_preflight_id"),
        "source_request_id": boundary.get("source_request_id"),
        "status": intake_status,
        "ready_for_authorization_request_intake": intake_ready,
        "ready_for_database_apply_now": False,
        "request_scope": "future_explicit_db_apply_authorization_only",
        "target_file": target_file,
        "expected_sha256": expected_sha256,
        "actual_sha256": actual_sha256,
        "hash_matches": hash_matches,
        "requires_new_explicit_db_apply_authorization": True,
        "requires_fresh_production_truth_in_future_run": True,
        "operator_secret_boundary": "future_shell_only",
        "reads_secret_in_preview": False,
        "writes_script_in_preview": False,
        "executes_shell_in_preview": False,
        "executes_sql_in_preview": False,
        "writes_database_in_preview": False,
        "manual_review_mode": "exception_only",
    }
    authorization_envelope = {
        "mode": "request_intake_only",
        "accepts_authorization_request": intake_ready,
        "issues_database_apply_authorization": False,
        "ready_for_database_apply_now": False,
        "manual_review_mode": "exception_only",
        "failed_gate_route": "exception_review_only",
        "rejects_direct_database_apply": True,
    }
    passed_gate_count = sum(1 for gate in authorization_acceptance_gates if gate.get("passed"))

    return {
        "policy": AUTO_POLICY_DB_APPLY_AUTHORIZATION_REQUEST_INTAKE_POLICY,
        "result": intake_status,
        "success": bool(closeout.get("success")),
        "generated_at": closeout.get("generated_at"),
        "source_policy": closeout.get("policy"),
        "stats": closeout.get("stats") or {},
        "summary": {
            "authorization_request_intake_ready_count": 1 if intake_ready else 0,
            "required_request_evidence_count": len(required_request_evidence),
            "request_payload_required_field_count": len(request_payload_schema["required_fields"]),
            "authorization_acceptance_gate_count": len(authorization_acceptance_gates),
            "authorization_acceptance_pass_count": passed_gate_count,
            "authorization_acceptance_waiting_count": len(authorization_acceptance_gates) - passed_gate_count,
            "rejection_reason_count": len(rejection_reasons),
            "closeout_ready_count": summary.get("closeout_ready_count", 0),
            "closeout_check_count": summary.get("closeout_check_count", 0),
            "future_apply_boundary_count": summary.get("future_apply_boundary_count", 0),
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            LEGACY_REVIEW_REQUIRED_COUNT_KEY: summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY, 0),
        },
        "authorization_request_intake": authorization_request_intake,
        "authorization_envelope": authorization_envelope,
        "required_request_evidence": required_request_evidence,
        "request_payload_schema": request_payload_schema,
        "authorization_acceptance_gates": authorization_acceptance_gates,
        "rejection_reasons": rejection_reasons,
        "source_closeout_summary": summary,
        "safety": {
            "read_only_db_apply_authorization_request_intake": True,
            "reads_secret_in_preview": False,
            "writes_file": False,
            "writes_script_in_preview": False,
            "writes_artifact_in_preview": False,
            "executes_script": False,
            "executes_endpoint": False,
            "executes_migration": False,
            "executes_sql": False,
            "writes_database": False,
            "persists_receipt": False,
            "updates_mapping": False,
            "dispatches_telegram": False,
            "llm_calls_in_gate": False,
            "manual_review_mode": "exception_only",
        },
        "next_actions": [
            "Use this intake envelope to accept or reject a separate explicit DB apply authorization request.",
            "Keep the intake from issuing DB apply authorization; it only verifies request evidence completeness.",
            "Reject any payload that includes secrets, asks for direct DB apply, or skips fresh production truth.",
        ],
    }
