"""GitHub private backup evidence gate.

Builds a read-only gate from committed GitHub target snapshots. The gate is
deliberately conservative: a public probe hit is not considered a valid backup
because AWOOOI policy requires GitHub backup targets to be private.
"""

from __future__ import annotations

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

from src.services.snapshot_paths import default_security_dir

_DEFAULT_SECURITY_DIR = default_security_dir(Path(__file__))
_SCHEMA_VERSION = "github_target_private_backup_evidence_gate_v1"

_DECISION_FILE = "github-target-decision.snapshot.json"
_OWNER_RESPONSE_FILE = "github-target-owner-decision-response.snapshot.json"
_APPROVAL_PACKAGE_FILE = "github-target-repo-approval-package.snapshot.json"
_PROBE_FILE = "github-target-probe.snapshot.json"
_CONNECTOR_READBACK_FILE = "github-target-connector-readback.snapshot.json"
_MISSING_SOURCE_READINESS_FILE = "github-target-missing-source-readiness.snapshot.json"
_EXECUTION_AUTHORIZATION_FILE = (
    "github-target-owner-execution-authorization.snapshot.json"
)
_CONTROLLED_EXECUTION_PREFLIGHT_FILE = (
    "github-target-controlled-execution-preflight.snapshot.json"
)
_OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_FILE = (
    "github-operator-unblock-governance-closure.snapshot.json"
)
_EXECUTION_AUTHORIZATION_SCHEMA_VERSION = (
    "github_target_owner_execution_authorization_v1"
)
_CONTROLLED_EXECUTION_PREFLIGHT_SCHEMA_VERSION = (
    "github_target_controlled_execution_preflight_v1"
)
_OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_SCHEMA_VERSION = (
    "github_operator_unblock_governance_closure_v1"
)
_GITHUB_WRITE_CHANNEL_RECHECK_COMMANDS = [
    "gh api /user --jq '{login:.login}'",
    "git push --dry-run origin HEAD:refs/heads/codex-github-write-channel-readonly-check",
]
_GITHUB_OPERATOR_UNBLOCK_ACTIONS = [
    "complete_github_account_suspension_appeal_or_provide_authorized_writable_namespace",
    "refresh_local_github_cli_login_without_sharing_tokens_or_cookies",
    "rerun_github_write_channel_dry_run_before_create_or_refs_sync",
]
_GITHUB_OPERATOR_STILL_FORBIDDEN = [
    "do_not_paste_pat_token_private_key_cookie_session_or_authorization_header",
    "do_not_collect_private_clone_url_or_credential_value",
    "do_not_force_push_delete_refs_or_change_public_visibility",
]
_PREFLIGHT_SCHEMA_VERSION = "github_target_owner_response_intake_preflight_v1"
_PREFLIGHT_MODE = "validate_owner_response_only_no_persist_no_github_write"
_SAFE_CREDENTIAL_REVIEW_SCHEMA_VERSION = (
    "github_target_safe_credential_evidence_ref_validation_result_v1"
)
_SAFE_CREDENTIAL_REVIEW_MODE = (
    "validate_redacted_evidence_refs_only_no_persist_no_github_write"
)
_SAFE_CREDENTIAL_REVIEW_ENDPOINT = (
    "/api/v1/agents/"
    "github-target-safe-credential-evidence-reviewer-validation/validate-redacted-refs"
)
_SAFE_CREDENTIAL_REVIEW_ACCEPT_DECISION = (
    "accept_redacted_evidence_refs_for_reviewer_validation"
)
_SAFE_CREDENTIAL_REVIEW_REQUIRED_FIELDS = (
    "template_id",
    "github_repo",
    "reviewer_role_or_team",
    "decision",
    "decision_reason",
    "evidence_ref_type",
    "redacted_evidence_refs",
)
_SAFE_CREDENTIAL_REVIEW_OPTIONAL_FIELDS = {
    "affected_scope",
    "evidence_refs",
    "followup_owner",
    "redaction_status",
    "response_id",
    "source_system",
    "submission_mode",
    "validation_plan",
}
_SUBMISSION_METADATA_FIELDS = {
    "github_repo",
    "response_id",
    "submission_mode",
    "template_id",
}
_FORBIDDEN_KEY_FRAGMENTS = {
    "api_request_body",
    "authorization_header",
    "cookie",
    "credential",
    "db_dump",
    "deploy_key",
    "git_object_pack",
    "password",
    "private_clone_url",
    "private_key",
    "repo_archive",
    "repo_creation_command",
    "requested_action",
    "requested_actions",
    "runtime_action",
    "runtime_execution",
    "refs_sync",
    "delete_refs",
    "force_push",
    "tag_rewrite",
    "github_primary_switch",
    "secret_value",
    "session",
    "token_value",
    "visibility_change_command",
    "workflow_trigger",
    "write_or_admin_api_request",
}
_RUNTIME_ACTION_TERMS = {
    "change_repo_visibility",
    "create_github_repo",
    "delete_refs",
    "force_push",
    "github_primary_switch",
    "push_refs",
    "refs_sync",
    "refs_sync_or_delete_request",
    "repo_creation_command",
    "requested_action",
    "requested_actions",
    "runtime_action",
    "runtime_execution",
    "switch_github_primary",
    "tag_rewrite",
    "visibility_change_command",
    "workflow_trigger",
    "write_or_admin_api_request",
}
_SENSITIVE_VALUE_PATTERNS = (
    ("github_token", re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{20,}\b")),
    ("github_fine_grained_token", re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b")),
    ("private_key_block", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
    ("credentialed_url", re.compile(r"[a-z][a-z0-9+.-]*://[^/\s:@]+:[^@\s]+@")),
    ("raw_internal_lan_address", re.compile(r"\b192\.168\.0\.\d+\b")),
)


def load_latest_github_target_private_backup_evidence_gate(
    security_dir: Path | None = None,
) -> dict[str, Any]:
    """Load committed GitHub snapshots and return a private-backup gate."""
    directory = security_dir or _DEFAULT_SECURITY_DIR
    decision = _load_snapshot(directory / _DECISION_FILE)
    owner_response = _load_snapshot(directory / _OWNER_RESPONSE_FILE)
    approval_package = _load_snapshot(directory / _APPROVAL_PACKAGE_FILE)
    probe = _load_snapshot(directory / _PROBE_FILE)
    connector_readback = _load_optional_snapshot(directory / _CONNECTOR_READBACK_FILE)
    missing_source_readiness = _load_optional_snapshot(
        directory / _MISSING_SOURCE_READINESS_FILE
    )
    execution_authorization = _load_optional_snapshot(
        directory / _EXECUTION_AUTHORIZATION_FILE
    )
    controlled_execution_preflight = _load_optional_snapshot(
        directory / _CONTROLLED_EXECUTION_PREFLIGHT_FILE
    )
    operator_unblock_governance_closure = _load_optional_snapshot(
        directory / _OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_FILE
    )

    _require_source_contracts(
        decision=decision,
        owner_response=owner_response,
        approval_package=approval_package,
        probe=probe,
        connector_readback=connector_readback,
        missing_source_readiness=missing_source_readiness,
        execution_authorization=execution_authorization,
        controlled_execution_preflight=controlled_execution_preflight,
        operator_unblock_governance_closure=operator_unblock_governance_closure,
    )
    return build_github_target_private_backup_evidence_gate(
        decision=decision,
        owner_response=owner_response,
        approval_package=approval_package,
        probe=probe,
        connector_readback=connector_readback,
        missing_source_readiness=missing_source_readiness,
        execution_authorization=execution_authorization,
        controlled_execution_preflight=controlled_execution_preflight,
        operator_unblock_governance_closure=operator_unblock_governance_closure,
    )


def load_latest_github_target_controlled_execution_preflight(
    security_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the GitHub controlled execution preflight readback."""
    return load_latest_github_target_private_backup_evidence_gate(security_dir)[
        "controlled_execution_preflight"
    ]


def preflight_github_target_owner_response_submission(
    submission: dict[str, Any],
    security_dir: Path | None = None,
) -> dict[str, Any]:
    """Validate an owner response candidate without storing or executing it."""
    gate = load_latest_github_target_private_backup_evidence_gate(security_dir)
    intake = _dict(gate.get("owner_response_intake_readiness"))
    target_by_template = {
        str(target.get("owner_response_template_id")): _dict(target)
        for target in _list(gate.get("targets"))
        if target.get("owner_response_template_id")
    }
    payload = _dict(submission)
    allowed_modes = set(_strings(intake.get("allowed_submission_modes")))
    allowed_fields = set(_strings(intake.get("allowed_response_fields")))
    forbidden_payloads = set(_strings(intake.get("forbidden_payloads")))
    still_forbidden = set(_strings(intake.get("still_forbidden")))

    submission_mode = str(payload.get("submission_mode") or "")
    candidate_responses = [_dict(row) for row in _list(payload.get("responses"))]
    mode_allowed = submission_mode in allowed_modes
    global_scan_payload = {
        key: value for key, value in payload.items() if key != "responses"
    }
    global_hits = _forbidden_payload_hits(
        global_scan_payload,
        forbidden_payloads=forbidden_payloads | still_forbidden,
    )
    response_results = [
        _preflight_owner_response_item(
            response=response,
            submission_mode=submission_mode,
            mode_allowed=mode_allowed,
            target_by_template=target_by_template,
            allowed_fields=allowed_fields,
            forbidden_payloads=forbidden_payloads | still_forbidden,
        )
        for response in candidate_responses
    ]
    passed_count = sum(
        1 for row in response_results if row["accepted_for_read_only_intake"] is True
    )
    blocked_count = len(response_results) - passed_count
    global_blockers: list[str] = []
    if not mode_allowed:
        global_blockers.append("submission_mode_not_allowed")
    if not candidate_responses:
        global_blockers.append("response_items_missing")
    if global_hits:
        global_blockers.append("forbidden_payload_detected")

    preflight_passed = (
        not global_blockers and candidate_responses and blocked_count == 0
    )
    return {
        "schema_version": _PREFLIGHT_SCHEMA_VERSION,
        "generated_at": gate.get("generated_at", ""),
        "status": "ready_for_read_only_owner_response_intake"
        if preflight_passed
        else "blocked_owner_response_intake_preflight",
        "mode": _PREFLIGHT_MODE,
        "summary": {
            "candidate_response_item_count": len(candidate_responses),
            "preflight_passed_response_item_count": passed_count,
            "preflight_blocked_response_item_count": blocked_count,
            "forbidden_payload_hit_count": len(global_hits)
            + sum(len(row["forbidden_hits"]) for row in response_results),
            "unsupported_field_count": sum(
                len(row["unsupported_fields"]) for row in response_results
            ),
            "missing_required_field_count": sum(
                len(row["missing_required_fields"]) for row in response_results
            ),
            "owner_response_received_count": 0,
            "owner_response_accepted_count": 0,
            "safe_credential_accepted_evidence_count": 0,
            "github_missing_target_create_private_repo_ready_count": gate["summary"][
                "github_missing_target_create_private_repo_ready_count"
            ],
            "github_missing_target_refs_sync_ready_count": gate["summary"][
                "github_missing_target_refs_sync_ready_count"
            ],
            "execution_authorized": False,
            "write_performed": False,
            "github_api_write_allowed": False,
            "repo_creation_authorized": False,
            "visibility_change_authorized": False,
            "refs_sync_authorized": False,
            "secret_value_collection_allowed": False,
        },
        "submission_mode": submission_mode,
        "submission_mode_allowed": mode_allowed,
        "allowed_submission_modes": sorted(allowed_modes),
        "global_blockers": global_blockers,
        "global_forbidden_hits": global_hits,
        "responses": response_results,
        "operation_boundaries": {
            "preflight_only": True,
            "persist_submission_allowed": False,
            "read_only_markdown_response_allowed": True,
            "redacted_metadata_pointer_allowed": True,
            "github_api_write_allowed": False,
            "repo_creation_allowed": False,
            "visibility_change_allowed": False,
            "refs_sync_allowed": False,
            "workflow_trigger_allowed": False,
            "private_clone_url_collection_allowed": False,
            "secret_value_collection_allowed": False,
        },
        "authorization_flags": {
            "owner_response_execution_authorized": False,
            "repo_creation_authorized": False,
            "visibility_change_authorized": False,
            "refs_sync_authorized": False,
            "workflow_trigger_authorized": False,
            "secret_value_collection_allowed": False,
            "private_clone_url_collection_allowed": False,
        },
    }


def validate_github_target_safe_credential_evidence_refs(
    submission: dict[str, Any],
    security_dir: Path | None = None,
) -> dict[str, Any]:
    """Validate redacted safe-credential evidence refs without persisting them."""
    gate = load_latest_github_target_private_backup_evidence_gate(security_dir)
    safe_intake = _dict(gate.get("safe_credential_evidence_intake_readiness"))
    owner_intake = _dict(gate.get("owner_response_intake_readiness"))
    payload = _dict(submission)
    allowed_modes = set(_strings(safe_intake.get("allowed_submission_modes")))
    allowed_ref_types = set(_strings(safe_intake.get("allowed_evidence_ref_types")))
    forbidden_payloads = (
        set(_strings(safe_intake.get("forbidden_payloads")))
        | set(_strings(owner_intake.get("still_forbidden")))
        | _RUNTIME_ACTION_TERMS
    )
    target_by_template = {
        str(target.get("owner_response_template_id")): _dict(target)
        for target in _list(gate.get("targets"))
        if target.get("owner_response_template_id")
    }

    submission_mode = str(payload.get("submission_mode") or "")
    candidate_items = [
        _dict(row) for row in _list(payload.get("evidence_ref_submissions"))
    ]
    if not candidate_items:
        candidate_items = [_dict(row) for row in _list(payload.get("responses"))]

    mode_allowed = submission_mode in allowed_modes
    global_scan_payload = {
        key: value
        for key, value in payload.items()
        if key not in {"evidence_ref_submissions", "responses"}
    }
    global_hits = _forbidden_payload_hits(
        global_scan_payload,
        forbidden_payloads=forbidden_payloads,
    )
    global_runtime_hits = _runtime_action_hits(global_hits)
    item_results = [
        _validate_safe_credential_evidence_ref_item(
            item=item,
            submission_mode=submission_mode,
            mode_allowed=mode_allowed,
            target_by_template=target_by_template,
            allowed_ref_types=allowed_ref_types,
            forbidden_payloads=forbidden_payloads,
        )
        for item in candidate_items
    ]
    passed_count = sum(
        1 for row in item_results if row["accepted_for_readonly_review"] is True
    )
    runtime_rejected_count = sum(
        1 for row in item_results if row["runtime_action_rejected"] is True
    ) + (1 if global_runtime_hits else 0)
    quarantined_count = sum(1 for row in item_results if row["quarantined"] is True) + (
        1 if global_hits and not global_runtime_hits else 0
    )
    blocked_count = len(item_results) - passed_count

    global_blockers: list[str] = []
    if not mode_allowed:
        global_blockers.append("submission_mode_not_allowed")
    if not candidate_items:
        global_blockers.append("redacted_evidence_ref_items_missing")
    if global_runtime_hits:
        global_blockers.append("runtime_action_request_detected")
    elif global_hits:
        global_blockers.append("forbidden_payload_detected")

    if runtime_rejected_count:
        status_value = "reject_runtime_action_request"
    elif quarantined_count:
        status_value = "quarantine_sensitive_payload"
    elif global_blockers or blocked_count:
        status_value = "request_redacted_evidence_ref_supplement"
    else:
        status_value = "accepted_for_readonly_safe_credential_evidence_review_only"

    accepted = (
        status_value == "accepted_for_readonly_safe_credential_evidence_review_only"
    )
    return {
        "schema_version": _SAFE_CREDENTIAL_REVIEW_SCHEMA_VERSION,
        "contract_schema_version": gate["schema_version"],
        "generated_at": gate.get("generated_at", ""),
        "status": status_value,
        "mode": _SAFE_CREDENTIAL_REVIEW_MODE,
        "outcome_lane": status_value,
        "accepted_for_readonly_review": accepted,
        "reviewer_validation_passed": accepted,
        "quarantined": status_value == "quarantine_sensitive_payload",
        "runtime_action_rejected": status_value == "reject_runtime_action_request",
        "submission_mode": submission_mode,
        "submission_mode_allowed": mode_allowed,
        "allowed_submission_modes": sorted(allowed_modes),
        "global_blockers": global_blockers,
        "global_forbidden_hits": global_hits,
        "summary": {
            "candidate_evidence_ref_item_count": len(candidate_items),
            "reviewer_validation_passed_count": passed_count,
            "reviewer_validation_blocked_count": blocked_count,
            "reviewer_validation_quarantined_count": quarantined_count,
            "runtime_action_rejected_count": runtime_rejected_count,
            "forbidden_payload_hit_count": len(global_hits)
            + sum(len(row["forbidden_hits"]) for row in item_results),
            "unsafe_evidence_ref_hit_count": sum(
                len(row["evidence_ref_hits"]) for row in item_results
            ),
            "missing_required_field_count": sum(
                len(row["missing_required_fields"]) for row in item_results
            ),
            "safe_credential_evidence_submission_received_count": len(candidate_items),
            "safe_credential_evidence_submission_accepted_count": passed_count,
            "safe_credential_accepted_evidence_count": 0,
            "private_backup_verified_count": gate["summary"][
                "private_backup_verified_count"
            ],
            "github_missing_target_create_private_repo_ready_count": gate["summary"][
                "github_missing_target_create_private_repo_ready_count"
            ],
            "github_missing_target_refs_sync_ready_count": gate["summary"][
                "github_missing_target_refs_sync_ready_count"
            ],
            "execution_ready_count": gate["summary"]["execution_ready_count"],
            "blocked_target_count": gate["summary"]["blocked_target_count"],
            "payload_persisted": False,
            "safe_credential_accepted_updated": False,
            "github_api_write_allowed": False,
            "repo_creation_authorized": False,
            "visibility_change_authorized": False,
            "refs_sync_authorized": False,
            "workflow_trigger_authorized": False,
            "private_clone_url_collection_allowed": False,
            "secret_value_collection_allowed": False,
            "execution_authorized": False,
        },
        "evidence_ref_submissions": item_results,
        "boundary_markers": [
            "github_safe_credential_evidence_review_no_persist=true",
            f"github_safe_credential_evidence_review_passed_count={passed_count}",
            f"github_safe_credential_evidence_review_quarantined_count={quarantined_count}",
            "github_safe_credential_accepted_evidence_count=0",
            "github_safe_credential_accepted_updated=false",
            "github_repo_creation_authorized=false",
            "github_visibility_change_authorized=false",
            "github_refs_sync_authorized=false",
            "github_workflow_trigger_authorized=false",
            "github_private_clone_url_collection_allowed=false",
            "github_secret_value_collection_allowed=false",
            "runtime_execution_authorized=false",
            "not_authorization=true",
        ],
        "boundaries": {
            "payload_persisted": False,
            "github_api_write_allowed": False,
            "repo_creation_authorized": False,
            "visibility_change_authorized": False,
            "refs_sync_authorized": False,
            "workflow_trigger_authorized": False,
            "private_clone_url_collection_allowed": False,
            "secret_value_collection_allowed": False,
            "raw_payload_storage_allowed": False,
            "safe_credential_accepted_updated": False,
            "runtime_execution_authorized": False,
            "not_authorization": True,
        },
        "next_gate": "private_backup_post_review_readback"
        if accepted
        else "redacted_evidence_ref_fix_and_resubmit",
    }


def build_github_target_private_backup_evidence_gate(
    *,
    decision: dict[str, Any],
    owner_response: dict[str, Any],
    approval_package: dict[str, Any],
    probe: dict[str, Any],
    connector_readback: dict[str, Any] | None = None,
    missing_source_readiness: dict[str, Any] | None = None,
    execution_authorization: dict[str, Any] | None = None,
    controlled_execution_preflight: dict[str, Any] | None = None,
    operator_unblock_governance_closure: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build the read-only gate response from source-control snapshots."""
    connector_payload = _dict(connector_readback)
    owner_readback = _dict(connector_payload.get("owner_readback"))
    missing_payload = _dict(missing_source_readiness)
    missing_summary = _dict(missing_payload.get("summary"))
    authorization_payload = _dict(execution_authorization)
    execution_preflight_payload = _dict(controlled_execution_preflight)
    governance_payload = _dict(operator_unblock_governance_closure)
    authorization_summary = _execution_authorization_summary(authorization_payload)
    execution_authorized = (
        authorization_summary["authorization_present"]
        and authorization_summary["repo_creation_authorized"]
        and authorization_summary["visibility_change_authorized"]
        and authorization_summary["refs_sync_authorized"]
        and authorization_summary["workflow_trigger_authorized"]
    )
    decisions = [_dict(row) for row in _list(decision.get("decisions"))]
    probe_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(probe.get("candidates"))
        if row.get("github_repo")
    }
    package_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(approval_package.get("approval_items"))
        if row.get("github_repo")
    }
    connector_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(connector_payload.get("targets"))
        if row.get("github_repo")
    }
    missing_source_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(missing_payload.get("targets"))
        if row.get("github_repo")
    }
    authorization_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(authorization_payload.get("authorized_targets"))
        if row.get("github_repo")
    }
    execution_preflight_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(execution_preflight_payload.get("targets"))
        if row.get("github_repo")
    }
    owner_summary = _dict(owner_response.get("summary"))
    owner_response_intake_readiness = _owner_response_intake_readiness(owner_response)
    safe_credential_evidence_intake_readiness = (
        _safe_credential_evidence_intake_readiness(
            owner_response=owner_response,
            required_target_count=len(
                [row for row in decisions if row.get("approval_required") is True]
            ),
        )
    )
    owner_template_by_repo = {
        str(row.get("github_repo")): _dict(row)
        for row in _list(owner_response.get("response_templates"))
        if row.get("github_repo")
    }

    targets = [
        _build_target(
            decision=row,
            probe=probe_by_repo.get(str(row.get("github_repo")), {}),
            approval_item=package_by_repo.get(str(row.get("github_repo")), {}),
            connector_readback=connector_by_repo.get(str(row.get("github_repo")), {}),
            missing_source_readiness=missing_source_by_repo.get(
                str(row.get("github_repo")), {}
            ),
            owner_response_template=owner_template_by_repo.get(
                str(row.get("github_repo")), {}
            ),
            execution_authorization=authorization_by_repo.get(
                str(row.get("github_repo")), {}
            ),
            controlled_execution_preflight=execution_preflight_by_repo.get(
                str(row.get("github_repo")), {}
            ),
            global_execution_authorized=execution_authorized,
        )
        for row in decisions
    ]

    approval_required_targets = [row for row in targets if row["approval_required"]]
    public_probe_visible_targets = [
        row
        for row in approval_required_targets
        if row["visibility_evidence_status"]
        == "blocked_public_probe_visible_private_evidence_required"
    ]
    not_found_or_private_targets = [
        row
        for row in approval_required_targets
        if row["visibility_evidence_status"] == "blocked_private_or_absent_not_verified"
    ]
    external_scope_targets = [
        row
        for row in targets
        if row["visibility_evidence_status"] == "external_scope_not_backup_target"
    ]
    blocked_targets = [
        row for row in approval_required_targets if not row["execution_ready"]
    ]
    controlled_preflight = _controlled_execution_preflight_readiness(
        payload=execution_preflight_payload,
        targets=targets,
        authorization_summary=authorization_summary,
    )
    internal_governance_writeback = (
        _github_operator_unblock_internal_governance_writeback(
            payload=governance_payload,
            controlled_preflight=controlled_preflight,
        )
    )
    controlled_preflight["internal_governance_writeback"] = (
        internal_governance_writeback
    )

    private_backup_verified_count = sum(
        1 for row in approval_required_targets if row["private_backup_verified"]
    )
    forbidden_actions = sorted(
        {item for row in targets for item in row["forbidden_actions"]}
    )

    return {
        "schema_version": _SCHEMA_VERSION,
        "generated_at": str(
            authorization_payload.get("generated_at") or _generated_at(owner_response)
        ),
        "status": "owner_authorized_controlled_execution_preflight_ready"
        if execution_authorized
        else (
            "blocked_public_visibility_and_safe_credential_evidence_required"
            if public_probe_visible_targets
            else "blocked_private_visibility_and_safe_credential_evidence_required"
        ),
        "mode": "owner_authorized_controlled_execution_no_secret_plaintext"
        if execution_authorized
        else "read_only_private_backup_evidence_gate",
        "source_reviews": {
            "target_decision": f"docs/security/{_DECISION_FILE}",
            "owner_decision_response": f"docs/security/{_OWNER_RESPONSE_FILE}",
            "approval_package": f"docs/security/{_APPROVAL_PACKAGE_FILE}",
            "github_target_probe": f"docs/security/{_PROBE_FILE}",
            "github_connector_readback": f"docs/security/{_CONNECTOR_READBACK_FILE}",
            "github_missing_source_readiness": f"docs/security/{_MISSING_SOURCE_READINESS_FILE}",
            "github_owner_execution_authorization": f"docs/security/{_EXECUTION_AUTHORIZATION_FILE}",
            "github_controlled_execution_preflight": f"docs/security/{_CONTROLLED_EXECUTION_PREFLIGHT_FILE}",
            "github_operator_unblock_governance_closure": f"docs/security/{_OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_FILE}",
        },
        "summary": {
            "target_decision_count": len(targets),
            "approval_required_target_count": len(approval_required_targets),
            "approval_package_item_count": len(
                _list(approval_package.get("approval_items"))
            ),
            "github_connector_owner_visible_repository_count": _int(
                owner_readback.get("visible_repository_count")
            ),
            "github_connector_owner_visible_private_repository_count": _int(
                owner_readback.get("visible_private_repository_count")
            ),
            "github_connector_readback_count": len(
                _list(connector_payload.get("targets"))
            ),
            "github_connector_private_visibility_count": sum(
                1
                for row in _list(connector_payload.get("targets"))
                if _dict(row).get("private_visibility_verified") is True
            ),
            "github_connector_not_found_or_inaccessible_count": sum(
                1
                for row in _list(connector_payload.get("targets"))
                if _dict(row).get("readback_status") == "not_found_or_inaccessible"
            ),
            "github_missing_target_resolution_count": len(
                _list(missing_payload.get("targets"))
            ),
            "github_missing_target_gitea_source_candidate_count": _int(
                missing_summary.get("gitea_source_candidate_count")
            ),
            "github_missing_target_internal_remote_source_candidate_count": _int(
                missing_summary.get("internal_remote_source_candidate_count")
            ),
            "github_missing_target_local_worktree_candidate_count": _int(
                missing_summary.get("local_worktree_candidate_count")
            ),
            "github_missing_target_canonical_source_ambiguous_count": _int(
                missing_summary.get("canonical_source_ambiguous_count")
            ),
            "github_missing_target_create_private_repo_ready_count": _int(
                missing_summary.get("create_private_repo_ready_count")
            ),
            "github_missing_target_refs_sync_ready_count": _int(
                missing_summary.get("refs_sync_ready_count")
            ),
            "public_probe_visible_target_count": len(public_probe_visible_targets),
            "not_found_or_private_target_count": len(not_found_or_private_targets),
            "private_backup_verified_count": private_backup_verified_count,
            "private_visibility_verified_count": private_backup_verified_count,
            "private_visibility_evidence_missing_count": len(approval_required_targets)
            - private_backup_verified_count,
            "safe_credential_required_count": len(approval_required_targets),
            "safe_credential_accepted_evidence_count": 0,
            "safe_credential_execution_override_authorized": execution_authorized,
            "safe_credential_evidence_requirement_overridden_for_execution": execution_authorized,
            "safe_credential_evidence_intake_ready": safe_credential_evidence_intake_readiness[
                "intake_ready"
            ],
            "safe_credential_required_redacted_evidence_ref_count": safe_credential_evidence_intake_readiness[
                "required_redacted_evidence_ref_count"
            ],
            "safe_credential_evidence_ref_rule_count": safe_credential_evidence_intake_readiness[
                "evidence_ref_rule_count"
            ],
            "safe_credential_redaction_example_count": safe_credential_evidence_intake_readiness[
                "redaction_example_count"
            ],
            "safe_credential_forbidden_payload_count": safe_credential_evidence_intake_readiness[
                "forbidden_payload_count"
            ],
            "safe_credential_quarantine_lane_count": safe_credential_evidence_intake_readiness[
                "quarantine_lane_count"
            ],
            "safe_credential_raw_payload_storage_allowed": False,
            "safe_credential_reviewer_validation_ready": safe_credential_evidence_intake_readiness[
                "reviewer_validation_ready"
            ],
            "safe_credential_reviewer_validation_required_field_count": safe_credential_evidence_intake_readiness[
                "reviewer_validation_required_field_count"
            ],
            "safe_credential_reviewer_validation_passed_count": 0,
            "safe_credential_reviewer_validation_quarantined_count": 0,
            "owner_response_received_count": _int(
                owner_summary.get("received_response_count")
            ),
            "owner_response_accepted_count": _int(
                owner_summary.get("accepted_response_count")
            ),
            "owner_response_request_ready": owner_response_intake_readiness[
                "request_ready"
            ],
            "owner_response_required_response_item_count": owner_response_intake_readiness[
                "required_response_item_count"
            ],
            "owner_response_requested_template_count": owner_response_intake_readiness[
                "requested_template_count"
            ],
            "owner_response_template_count": owner_response_intake_readiness[
                "response_template_count"
            ],
            "owner_response_allowed_response_field_count": owner_response_intake_readiness[
                "allowed_response_field_count"
            ],
            "owner_response_forbidden_payload_count": owner_response_intake_readiness[
                "forbidden_payload_count"
            ],
            "owner_response_collection_check_count": owner_response_intake_readiness[
                "collection_check_count"
            ],
            "owner_response_intake_preflight_check_count": owner_response_intake_readiness[
                "intake_preflight_check_count"
            ],
            "owner_response_request_execution_authorized": False,
            "github_target_owner_response_handoff_not_approval": True,
            "owner_execution_authorization_received_count": authorization_summary[
                "authorization_received_count"
            ],
            "owner_execution_authorized_target_count": authorization_summary[
                "authorized_target_count"
            ],
            "owner_execution_authorization_status": authorization_summary["status"],
            "owner_execution_authorization_source": authorization_summary[
                "authorization_source"
            ],
            "owner_execution_controlled_preflight_required_count": sum(
                1
                for row in approval_required_targets
                if row["controlled_preflight_required"] is True
            ),
            "post_execution_readback_required_count": sum(
                1
                for row in approval_required_targets
                if row["post_execution_readback_required"] is True
            ),
            "github_missing_target_create_private_repo_authorized_count": authorization_summary[
                "github_missing_target_create_private_repo_authorized_count"
            ],
            "github_missing_target_refs_sync_authorized_count": authorization_summary[
                "github_missing_target_refs_sync_authorized_count"
            ],
            "github_controlled_execution_preflight_ready": controlled_preflight[
                "preflight_ready"
            ],
            "github_write_channel_ready": controlled_preflight[
                "github_write_channel_ready"
            ],
            "github_account_status": controlled_preflight["github_account_status"],
            "github_account_suspended": controlled_preflight[
                "github_account_suspended"
            ],
            "github_api_forbidden_count": controlled_preflight[
                "github_api_forbidden_count"
            ],
            "github_create_repo_channel_ready": controlled_preflight[
                "github_create_repo_channel_ready"
            ],
            "github_refs_sync_channel_ready": controlled_preflight[
                "github_refs_sync_channel_ready"
            ],
            "github_missing_target_controlled_apply_ready_count": controlled_preflight[
                "controlled_apply_ready_count"
            ],
            "github_missing_target_blocked_preflight_count": controlled_preflight[
                "blocked_preflight_target_count"
            ],
            "github_missing_target_github_404_count": controlled_preflight[
                "github_connector_missing_target_404_count"
            ],
            "github_operator_unblock_internal_governance_ready": internal_governance_writeback[
                "ready"
            ],
            "github_operator_unblock_mcp_evidence_packet_count": internal_governance_writeback[
                "mcp_evidence_packet_count"
            ],
            "github_operator_unblock_rag_evidence_ref_count": internal_governance_writeback[
                "rag_evidence_ref_count"
            ],
            "github_operator_unblock_km_writeback_ready_count": internal_governance_writeback[
                "km_writeback_ready_count"
            ],
            "github_operator_unblock_playbook_writeback_ready_count": internal_governance_writeback[
                "playbook_writeback_ready_count"
            ],
            "github_operator_unblock_timeline_log_ready_count": internal_governance_writeback[
                "timeline_log_ready_count"
            ],
            "github_operator_unblock_logbook_entry_count": internal_governance_writeback[
                "logbook_entry_count"
            ],
            "github_operator_unblock_github_write_performed": internal_governance_writeback[
                "github_write_performed"
            ],
            "execution_ready_count": sum(
                1 for row in approval_required_targets if row["execution_ready"]
            ),
            "blocked_target_count": len(blocked_targets),
            "external_scope_target_count": len(external_scope_targets),
            "forbidden_action_count": len(forbidden_actions),
            "repo_creation_authorized": authorization_summary[
                "repo_creation_authorized"
            ],
            "visibility_change_authorized": authorization_summary[
                "visibility_change_authorized"
            ],
            "refs_sync_authorized": authorization_summary["refs_sync_authorized"],
            "github_primary_switch_authorized": authorization_summary[
                "github_primary_switch_authorized"
            ],
            "workflow_modification_authorized": False,
            "workflow_trigger_authorized": authorization_summary[
                "workflow_trigger_authorized"
            ],
            "secret_value_collection_allowed": False,
            "private_clone_url_collection_allowed": False,
            "not_found_or_private_as_absent_allowed": authorization_summary[
                "not_found_or_private_as_absent_allowed"
            ],
            "public_repo_allowed": False,
        },
        "owner_response_intake_readiness": owner_response_intake_readiness,
        "safe_credential_evidence_intake_readiness": safe_credential_evidence_intake_readiness,
        "controlled_execution_preflight": controlled_preflight,
        "internal_governance_writeback": internal_governance_writeback,
        "targets": targets,
        "acceptance_requirements": _acceptance_requirements(owner_response),
        "rejection_rules": _rejection_rules(owner_response),
        "operation_boundaries": {
            "read_only_api_allowed": True,
            "github_api_write_allowed": authorization_summary[
                "github_api_write_allowed"
            ],
            "gitea_api_write_allowed": False,
            "repo_creation_allowed": authorization_summary["repo_creation_authorized"],
            "visibility_change_allowed": authorization_summary[
                "visibility_change_authorized"
            ],
            "refs_sync_allowed": authorization_summary["refs_sync_authorized"],
            "workflow_modification_allowed": False,
            "workflow_trigger_allowed": authorization_summary[
                "workflow_trigger_authorized"
            ],
            "github_write_channel_ready": controlled_preflight[
                "github_write_channel_ready"
            ],
            "controlled_apply_allowed": controlled_preflight["preflight_ready"],
            "github_primary_switch_allowed": False,
            "secret_value_collection_allowed": False,
            "private_clone_url_collection_allowed": False,
        },
        "authorization_flags": {
            "owner_execution_authorization_present": authorization_summary[
                "authorization_present"
            ],
            "repo_creation_authorized": authorization_summary[
                "repo_creation_authorized"
            ],
            "visibility_change_authorized": authorization_summary[
                "visibility_change_authorized"
            ],
            "refs_sync_authorized": authorization_summary["refs_sync_authorized"],
            "github_primary_switch_authorized": authorization_summary[
                "github_primary_switch_authorized"
            ],
            "workflow_modification_authorized": False,
            "workflow_trigger_authorized": authorization_summary[
                "workflow_trigger_authorized"
            ],
            "secret_value_collection_allowed": False,
            "private_clone_url_collection_allowed": False,
        },
    }


def _preflight_owner_response_item(
    *,
    response: dict[str, Any],
    submission_mode: str,
    mode_allowed: bool,
    target_by_template: dict[str, dict[str, Any]],
    allowed_fields: set[str],
    forbidden_payloads: set[str],
) -> dict[str, Any]:
    template_id = str(response.get("template_id") or "")
    target = target_by_template.get(template_id, {})
    required_fields = set(_strings(target.get("owner_response_required_fields")))
    acceptable_decisions = set(
        _strings(target.get("owner_response_acceptable_decisions"))
    )
    response_fields = set(response)
    supported_fields = allowed_fields | _SUBMISSION_METADATA_FIELDS
    unsupported_fields = sorted(response_fields - supported_fields)
    missing_required_fields = sorted(
        field
        for field in required_fields
        if not _has_response_value(response.get(field))
    )
    evidence_refs = sorted(
        set(_response_strings(response.get("redacted_evidence_refs")))
        | set(_response_strings(response.get("evidence_refs")))
    )
    decision = str(response.get("decision") or "")
    blockers: list[str] = []
    if not mode_allowed:
        blockers.append("submission_mode_not_allowed")
    if not target:
        blockers.append("unknown_or_unrequested_template_id")
    if unsupported_fields:
        blockers.append("unsupported_response_fields")
    if missing_required_fields:
        blockers.append("required_fields_missing")
    if acceptable_decisions and decision not in acceptable_decisions:
        blockers.append("decision_not_allowed_for_template")
    if not evidence_refs:
        blockers.append("redacted_evidence_refs_missing")

    forbidden_hits = _forbidden_payload_hits(
        response,
        forbidden_payloads=forbidden_payloads,
    )
    evidence_ref_hits = _evidence_ref_hits(evidence_refs)
    if forbidden_hits:
        blockers.append("forbidden_payload_detected")
    if evidence_ref_hits:
        blockers.append("unsafe_evidence_ref_detected")

    accepted = not blockers
    return {
        "template_id": template_id,
        "github_repo": str(
            response.get("github_repo") or target.get("github_repo") or ""
        ),
        "submission_mode": submission_mode,
        "status": "preflight_passed_read_only_intake_candidate"
        if accepted
        else "blocked_owner_response_candidate",
        "accepted_for_read_only_intake": accepted,
        "decision": decision,
        "allowed_decision_count": len(acceptable_decisions),
        "required_field_count": len(required_fields),
        "missing_required_fields": missing_required_fields,
        "unsupported_fields": unsupported_fields,
        "redacted_evidence_ref_count": len(evidence_refs),
        "redacted_evidence_refs": evidence_refs,
        "forbidden_hits": forbidden_hits,
        "evidence_ref_hits": evidence_ref_hits,
        "blockers": sorted(set(blockers)),
        "owner_response_received": False,
        "owner_response_accepted": False,
        "safe_credential_evidence_accepted": False,
        "execution_authorized": False,
        "repo_creation_authorized": False,
        "visibility_change_authorized": False,
        "refs_sync_authorized": False,
    }


def _validate_safe_credential_evidence_ref_item(
    *,
    item: dict[str, Any],
    submission_mode: str,
    mode_allowed: bool,
    target_by_template: dict[str, dict[str, Any]],
    allowed_ref_types: set[str],
    forbidden_payloads: set[str],
) -> dict[str, Any]:
    template_id = str(item.get("template_id") or "")
    target = target_by_template.get(template_id, {})
    github_repo = str(item.get("github_repo") or target.get("github_repo") or "")
    evidence_ref_type = str(item.get("evidence_ref_type") or "")
    decision = str(item.get("decision") or "")
    response_fields = set(item)
    supported_fields = (
        set(_SAFE_CREDENTIAL_REVIEW_REQUIRED_FIELDS)
        | _SAFE_CREDENTIAL_REVIEW_OPTIONAL_FIELDS
    )
    unsupported_fields = sorted(response_fields - supported_fields)
    missing_required_fields = sorted(
        field
        for field in _SAFE_CREDENTIAL_REVIEW_REQUIRED_FIELDS
        if not _has_response_value(item.get(field))
    )
    evidence_refs = sorted(set(_response_strings(item.get("redacted_evidence_refs"))))
    blockers: list[str] = []
    if not mode_allowed:
        blockers.append("submission_mode_not_allowed")
    if not target:
        blockers.append("unknown_or_unrequested_template_id")
    if (
        target
        and item.get("github_repo")
        and str(item.get("github_repo")) != str(target.get("github_repo"))
    ):
        blockers.append("github_repo_mismatch_for_template")
    if unsupported_fields:
        blockers.append("unsupported_evidence_ref_fields")
    if missing_required_fields:
        blockers.append("required_fields_missing")
    if evidence_ref_type not in allowed_ref_types:
        blockers.append("evidence_ref_type_not_allowed")
    if decision != _SAFE_CREDENTIAL_REVIEW_ACCEPT_DECISION:
        blockers.append("decision_not_allowed_for_safe_credential_review")
    if not evidence_refs:
        blockers.append("redacted_evidence_refs_missing")

    forbidden_hits = _forbidden_payload_hits(
        item, forbidden_payloads=forbidden_payloads
    )
    runtime_hits = _runtime_action_hits(forbidden_hits)
    evidence_ref_hits = _evidence_ref_hits(evidence_refs)
    if runtime_hits:
        blockers.append("runtime_action_request_detected")
    elif forbidden_hits:
        blockers.append("forbidden_payload_detected")
    if evidence_ref_hits:
        blockers.append("unsafe_evidence_ref_detected")

    accepted = not blockers
    return {
        "template_id": template_id,
        "github_repo": github_repo,
        "submission_mode": submission_mode,
        "status": "accepted_for_readonly_safe_credential_evidence_review_only"
        if accepted
        else "blocked_safe_credential_evidence_ref_candidate",
        "accepted_for_readonly_review": accepted,
        "reviewer_validation_passed": accepted,
        "quarantined": bool(forbidden_hits and not runtime_hits),
        "runtime_action_rejected": bool(runtime_hits),
        "decision": decision,
        "allowed_decisions": [_SAFE_CREDENTIAL_REVIEW_ACCEPT_DECISION],
        "evidence_ref_type": evidence_ref_type,
        "allowed_evidence_ref_types": sorted(allowed_ref_types),
        "required_field_count": len(_SAFE_CREDENTIAL_REVIEW_REQUIRED_FIELDS),
        "missing_required_fields": missing_required_fields,
        "unsupported_fields": unsupported_fields,
        "redacted_evidence_ref_count": len(evidence_refs),
        "redacted_evidence_refs": evidence_refs if not evidence_ref_hits else [],
        "evidence_ref_redacted_due_to_findings": bool(evidence_ref_hits),
        "forbidden_hits": forbidden_hits,
        "runtime_action_hits": runtime_hits,
        "evidence_ref_hits": evidence_ref_hits,
        "blockers": sorted(set(blockers)),
        "safe_credential_evidence_received": True,
        "safe_credential_evidence_accepted": False,
        "safe_credential_accepted_updated": False,
        "payload_persisted": False,
        "execution_authorized": False,
        "repo_creation_authorized": False,
        "visibility_change_authorized": False,
        "refs_sync_authorized": False,
        "workflow_trigger_authorized": False,
    }


def _build_target(
    *,
    decision: dict[str, Any],
    probe: dict[str, Any],
    approval_item: dict[str, Any],
    connector_readback: dict[str, Any],
    missing_source_readiness: dict[str, Any],
    owner_response_template: dict[str, Any],
    execution_authorization: dict[str, Any],
    controlled_execution_preflight: dict[str, Any],
    global_execution_authorized: bool,
) -> dict[str, Any]:
    github_repo = str(decision.get("github_repo") or "")
    probe_status = str(probe.get("status") or decision.get("probe_status") or "unknown")
    target_state = str(decision.get("target_state") or "unknown")
    approval_required = decision.get("approval_required") is True
    external_scope = not approval_required or target_state == "external_scope"
    private_visibility_verified = (
        not external_scope
        and connector_readback.get("readback_status") == "visible"
        and connector_readback.get("visibility") == "private"
        and connector_readback.get("private_visibility_verified") is True
    )
    visibility_status = _visibility_evidence_status(
        external_scope=external_scope,
        probe_status=probe_status,
        private_visibility_verified=private_visibility_verified,
    )
    owner_execution_authorized = (
        approval_required
        and global_execution_authorized
        and execution_authorization.get("target_execution_authorized") is True
    )
    repo_creation_authorized = (
        owner_execution_authorized
        and execution_authorization.get("create_private_repo_authorized") is True
    )
    visibility_change_authorized = (
        owner_execution_authorized
        and execution_authorization.get("visibility_change_authorized") is True
    )
    refs_sync_authorized = (
        owner_execution_authorized
        and execution_authorization.get("refs_sync_authorized") is True
    )
    workflow_trigger_authorized = (
        owner_execution_authorized
        and execution_authorization.get("workflow_trigger_authorized") is True
    )
    execution_ready = (
        owner_execution_authorized
        and visibility_change_authorized
        and refs_sync_authorized
        and workflow_trigger_authorized
    )
    controlled_apply_ready = (
        execution_ready
        and controlled_execution_preflight.get("controlled_apply_ready") is True
    )
    blockers = _target_blockers(
        visibility_status, approval_required, private_visibility_verified
    )
    if execution_ready:
        blockers = []
    forbidden_actions = _strings(approval_item.get("still_forbidden")) or [
        "create_github_repo",
        "change_repo_visibility",
        "push_refs",
        "delete_refs",
        "force_push",
        "switch_github_primary",
        "store_secret_value",
        "store_token_value",
    ]

    return {
        "github_repo": github_repo,
        "source_key": str(decision.get("source_key") or ""),
        "approval_required": approval_required,
        "probe_status": probe_status,
        "target_state": target_state,
        "risk": str(decision.get("risk") or "UNKNOWN"),
        "visibility_evidence_status": visibility_status,
        "github_connector_readback_status": str(
            connector_readback.get("readback_status") or "not_checked"
        ),
        "github_connector_visibility": connector_readback.get("visibility"),
        "missing_target_source_resolution_status": missing_source_readiness.get(
            "source_resolution_status"
        ),
        "missing_target_source_candidate_type": missing_source_readiness.get(
            "source_candidate_type"
        ),
        "missing_target_gitea_repo": missing_source_readiness.get("gitea_repo"),
        "missing_target_local_worktree_status": missing_source_readiness.get(
            "local_worktree_status"
        ),
        "missing_target_create_private_repo_ready": missing_source_readiness.get(
            "create_private_repo_ready"
        ),
        "missing_target_refs_sync_ready": missing_source_readiness.get(
            "refs_sync_ready"
        ),
        "missing_target_required_owner_decisions": _strings(
            missing_source_readiness.get("required_owner_decisions")
        ),
        "private_backup_verified": private_visibility_verified,
        "private_visibility_owner_evidence_ref": connector_readback.get("evidence_ref"),
        "safe_credential_evidence_status": "not_collected",
        "safe_credential_evidence_ref": None,
        "safe_credential_evidence_intake_ready": approval_required,
        "safe_credential_evidence_submission_status": (
            "owner_execution_authorized_post_apply_readback_pending"
            if owner_execution_authorized
            else (
                "waiting_redacted_evidence_ref" if approval_required else "not_required"
            )
        ),
        "safe_credential_required_redacted_evidence_ref": approval_required,
        "safe_credential_execution_override_authorized": owner_execution_authorized,
        "safe_credential_allowed_evidence_ref_types": [
            "repo_path",
            "snapshot_path",
            "redacted_metadata_pointer",
        ]
        if approval_required
        else [],
        "safe_credential_raw_payload_storage_allowed": False,
        "safe_credential_private_clone_url_collection_allowed": False,
        "safe_credential_secret_value_collection_allowed": False,
        "owner_response_template_id": owner_response_template.get("template_id"),
        "owner_response_submission_status": "waiting_owner_response"
        if approval_required
        else "not_required",
        "owner_response_requested_decision": owner_response_template.get(
            "requested_owner_decision"
        ),
        "owner_response_required_fields": _strings(
            owner_response_template.get("required_owner_fields")
        ),
        "owner_response_acceptable_decisions": _strings(
            owner_response_template.get("acceptable_decisions")
        ),
        "owner_response_minimum_evidence_refs": _strings(
            owner_response_template.get("minimum_evidence_refs")
        ),
        "owner_response_acceptance_criteria": _strings(
            owner_response_template.get("acceptance_criteria")
        ),
        "owner_response_rejection_conditions": _strings(
            owner_response_template.get("rejection_conditions")
        ),
        "owner_response_allowed_outputs": _strings(
            owner_response_template.get("allowed_outputs")
        ),
        "owner_response_execution_authorized": False,
        "owner_execution_authorized": owner_execution_authorized,
        "owner_execution_authorization_source": execution_authorization.get(
            "source_disposition"
        ),
        "controlled_execution_preflight_status": controlled_execution_preflight.get(
            "source_resolution_status"
        ),
        "controlled_execution_target_selector": controlled_execution_preflight.get(
            "target_selector"
        ),
        "controlled_execution_github_readback_status": controlled_execution_preflight.get(
            "github_readback_status"
        ),
        "source_preflight_ready": controlled_execution_preflight.get(
            "source_preflight_ready"
        ),
        "canonical_source_ready": controlled_execution_preflight.get(
            "canonical_source_ready"
        ),
        "canonical_source_ref": controlled_execution_preflight.get(
            "canonical_source_ref"
        ),
        "canonical_source_sha": controlled_execution_preflight.get(
            "canonical_source_sha"
        ),
        "source_probe_status": controlled_execution_preflight.get(
            "source_probe_status"
        ),
        "source_warnings": _strings(
            controlled_execution_preflight.get("source_warnings")
        ),
        "github_collision_preflight_ready": controlled_execution_preflight.get(
            "github_collision_preflight_ready"
        ),
        "create_private_repo_apply_ready": controlled_execution_preflight.get(
            "create_private_repo_apply_ready"
        ),
        "refs_sync_apply_ready": controlled_execution_preflight.get(
            "refs_sync_apply_ready"
        ),
        "controlled_apply_ready": controlled_apply_ready,
        "controlled_apply_blockers": _strings(
            controlled_execution_preflight.get("blockers")
        ),
        "controlled_preflight_required": bool(
            owner_execution_authorized
            and execution_authorization.get("controlled_preflight_required") is True
        ),
        "post_execution_readback_required": bool(
            owner_execution_authorized
            and execution_authorization.get("post_execution_readback_required") is True
        ),
        "owner_response_accepted": False,
        "refs_sync_ready": refs_sync_authorized,
        "execution_ready": execution_ready,
        "controlled_execution_ready": execution_ready,
        "blockers": blockers,
        "execution_pending_checks": [
            "controlled_preflight",
            "post_execution_private_visibility_and_refs_readback",
        ]
        if execution_ready
        else [],
        "evidence_refs": _strings(decision.get("evidence_refs")),
        "next_action": str(
            approval_item.get("approval_action")
            or decision.get("recommended_action")
            or ""
        ),
        "forbidden_actions": forbidden_actions,
        "repo_creation_authorized": repo_creation_authorized,
        "visibility_change_authorized": visibility_change_authorized,
        "refs_sync_authorized": refs_sync_authorized,
        "workflow_trigger_authorized": workflow_trigger_authorized,
        "github_primary_switch_authorized": False,
        "secret_values_collected": False,
    }


def _visibility_evidence_status(
    *,
    external_scope: bool,
    probe_status: str,
    private_visibility_verified: bool,
) -> str:
    if external_scope:
        return "external_scope_not_backup_target"
    if private_visibility_verified:
        return "verified_private_by_github_connector_readback"
    if probe_status == "exists":
        return "blocked_public_probe_visible_private_evidence_required"
    if probe_status == "not_found_or_private":
        return "blocked_private_or_absent_not_verified"
    return "blocked_probe_status_unknown"


def _target_blockers(
    visibility_status: str,
    approval_required: bool,
    private_visibility_verified: bool,
) -> list[str]:
    if not approval_required:
        return ["external_scope_not_backup_target"]
    blockers = [
        "safe_credential_evidence_missing",
        "owner_response_not_accepted",
        "refs_sync_not_authorized",
    ]
    if not private_visibility_verified:
        blockers.insert(0, "private_visibility_owner_evidence_missing")
    if visibility_status == "blocked_public_probe_visible_private_evidence_required":
        blockers.insert(0, "public_probe_visible_not_private_backup")
    if visibility_status == "blocked_private_or_absent_not_verified":
        blockers.insert(0, "not_found_or_private_requires_owner_evidence")
    return blockers


def _load_snapshot(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as handle:
        payload = json.load(handle)
    if not isinstance(payload, dict):
        raise ValueError(f"{path}: expected JSON object")
    return payload


def _load_optional_snapshot(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    return _load_snapshot(path)


def _require_source_contracts(
    *,
    decision: dict[str, Any],
    owner_response: dict[str, Any],
    approval_package: dict[str, Any],
    probe: dict[str, Any],
    connector_readback: dict[str, Any],
    missing_source_readiness: dict[str, Any],
    execution_authorization: dict[str, Any],
    controlled_execution_preflight: dict[str, Any],
    operator_unblock_governance_closure: dict[str, Any],
) -> None:
    _require_schema(decision, "github_target_decision_v1", _DECISION_FILE)
    _require_schema(
        owner_response, "github_target_owner_decision_response_v1", _OWNER_RESPONSE_FILE
    )
    _require_schema(
        approval_package,
        "github_target_repo_approval_package_v1",
        _APPROVAL_PACKAGE_FILE,
    )
    _require_schema(probe, "github_target_probe_v1", _PROBE_FILE)
    if connector_readback:
        _require_schema(
            connector_readback,
            "github_target_connector_readback_v1",
            _CONNECTOR_READBACK_FILE,
        )
    if missing_source_readiness:
        _require_schema(
            missing_source_readiness,
            "github_target_missing_source_readiness_v1",
            _MISSING_SOURCE_READINESS_FILE,
        )
    if execution_authorization:
        _require_schema(
            execution_authorization,
            _EXECUTION_AUTHORIZATION_SCHEMA_VERSION,
            _EXECUTION_AUTHORIZATION_FILE,
        )
    if controlled_execution_preflight:
        _require_schema(
            controlled_execution_preflight,
            _CONTROLLED_EXECUTION_PREFLIGHT_SCHEMA_VERSION,
            _CONTROLLED_EXECUTION_PREFLIGHT_FILE,
        )
    if operator_unblock_governance_closure:
        _require_schema(
            operator_unblock_governance_closure,
            _OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_SCHEMA_VERSION,
            _OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_FILE,
        )
    _require_decision_consistency(decision, _DECISION_FILE)
    _require_probe_consistency(probe, _PROBE_FILE)
    _require_approval_package_consistency(approval_package, _APPROVAL_PACKAGE_FILE)
    if connector_readback:
        _require_connector_readback_consistency(
            connector_readback, _CONNECTOR_READBACK_FILE
        )
    if missing_source_readiness:
        _require_missing_source_readiness_consistency(
            missing_source_readiness, _MISSING_SOURCE_READINESS_FILE
        )
    if execution_authorization:
        _require_execution_authorization_consistency(
            authorization=execution_authorization,
            decision=decision,
            missing_source_readiness=missing_source_readiness,
            label=_EXECUTION_AUTHORIZATION_FILE,
        )
    if controlled_execution_preflight:
        _require_controlled_execution_preflight_consistency(
            preflight=controlled_execution_preflight,
            missing_source_readiness=missing_source_readiness,
            label=_CONTROLLED_EXECUTION_PREFLIGHT_FILE,
        )
    if operator_unblock_governance_closure:
        _require_operator_unblock_governance_closure_consistency(
            payload=operator_unblock_governance_closure,
            label=_OPERATOR_UNBLOCK_GOVERNANCE_CLOSURE_FILE,
        )
    _require_owner_response_boundaries(owner_response, _OWNER_RESPONSE_FILE)


def _require_schema(payload: dict[str, Any], expected: str, label: str) -> None:
    actual = payload.get("schema_version")
    if actual != expected:
        raise ValueError(f"{label}: expected schema_version={expected}, got {actual!r}")


def _require_decision_consistency(payload: dict[str, Any], label: str) -> None:
    decisions = _list(payload.get("decisions"))
    if _int(payload.get("decision_count")) != len(decisions):
        raise ValueError(f"{label}: decision_count must equal decisions length")
    actual_approval_required = sum(
        1 for row in decisions if _dict(row).get("approval_required") is True
    )
    if _int(payload.get("approval_required_count")) != actual_approval_required:
        raise ValueError(f"{label}: approval_required_count must match decisions")


def _require_probe_consistency(payload: dict[str, Any], label: str) -> None:
    candidates = _list(payload.get("candidates"))
    if _int(payload.get("candidate_count")) != len(candidates):
        raise ValueError(f"{label}: candidate_count must equal candidates length")
    exists_count = sum(1 for row in candidates if _dict(row).get("status") == "exists")
    not_found_count = sum(
        1 for row in candidates if _dict(row).get("status") == "not_found_or_private"
    )
    if _int(payload.get("exists_count")) != exists_count:
        raise ValueError(f"{label}: exists_count must match candidates")
    if _int(payload.get("not_found_or_private_count")) != not_found_count:
        raise ValueError(f"{label}: not_found_or_private_count must match candidates")


def _require_approval_package_consistency(payload: dict[str, Any], label: str) -> None:
    approval_items = _list(payload.get("approval_items"))
    if _int(payload.get("package_count")) != len(approval_items):
        raise ValueError(f"{label}: package_count must equal approval_items length")


def _require_connector_readback_consistency(
    payload: dict[str, Any], label: str
) -> None:
    summary = _dict(payload.get("summary"))
    owner_readback = _dict(payload.get("owner_readback"))
    targets = [_dict(row) for row in _list(payload.get("targets"))]
    if _int(summary.get("target_count")) != len(targets):
        raise ValueError(f"{label}: summary.target_count must equal targets length")
    if owner_readback:
        visible_repositories = _list(owner_readback.get("visible_repositories"))
        if _int(owner_readback.get("visible_repository_count")) != len(
            visible_repositories
        ):
            raise ValueError(
                f"{label}: owner visible repository count must match visible repositories"
            )
        if _int(owner_readback.get("visible_private_repository_count")) > len(
            visible_repositories
        ):
            raise ValueError(
                f"{label}: owner private repository count cannot exceed visible repositories"
            )
    private_count = sum(
        1 for row in targets if row.get("private_visibility_verified") is True
    )
    not_found_count = sum(
        1
        for row in targets
        if row.get("readback_status") == "not_found_or_inaccessible"
    )
    if _int(summary.get("private_visibility_verified_count")) != private_count:
        raise ValueError(f"{label}: private visibility count must match targets")
    if _int(summary.get("not_found_or_inaccessible_count")) != not_found_count:
        raise ValueError(f"{label}: not found count must match targets")
    false_flags = {
        "github_api_write_performed",
        "repo_creation_performed",
        "visibility_change_performed",
        "refs_sync_performed",
        "secret_values_collected",
    }
    enabled = sorted(flag for flag in false_flags if summary.get(flag) is not False)
    enabled.extend(
        sorted(
            flag
            for flag in false_flags
            if owner_readback and owner_readback.get(flag) is not False
        )
    )
    if enabled:
        raise ValueError(
            f"{label}: connector readback must remain read-only: {enabled}"
        )


def _require_missing_source_readiness_consistency(
    payload: dict[str, Any], label: str
) -> None:
    summary = _dict(payload.get("summary"))
    targets = [_dict(row) for row in _list(payload.get("targets"))]
    if _int(summary.get("target_count")) != len(targets):
        raise ValueError(f"{label}: summary.target_count must equal targets length")
    create_ready = sum(
        1 for row in targets if row.get("create_private_repo_ready") is True
    )
    refs_ready = sum(1 for row in targets if row.get("refs_sync_ready") is True)
    owner_required = sum(
        1 for row in targets if row.get("owner_response_required") is True
    )
    if _int(summary.get("create_private_repo_ready_count")) != create_ready:
        raise ValueError(f"{label}: create ready count must match targets")
    if _int(summary.get("refs_sync_ready_count")) != refs_ready:
        raise ValueError(f"{label}: refs sync ready count must match targets")
    if _int(summary.get("owner_response_required_count")) != owner_required:
        raise ValueError(f"{label}: owner response required count must match targets")

    false_summary_flags = {
        "github_api_write_performed",
        "repo_creation_performed",
        "visibility_change_performed",
        "refs_sync_performed",
        "secret_values_collected",
    }
    enabled = sorted(
        flag for flag in false_summary_flags if summary.get(flag) is not False
    )
    boundaries = _dict(payload.get("operation_boundaries"))
    false_boundary_flags = {
        "github_api_write_allowed",
        "repo_creation_allowed",
        "visibility_change_allowed",
        "refs_sync_allowed",
        "secret_value_collection_allowed",
    }
    enabled.extend(
        sorted(
            flag for flag in false_boundary_flags if boundaries.get(flag) is not False
        )
    )
    if enabled:
        raise ValueError(
            f"{label}: missing source readiness must remain read-only: {enabled}"
        )


def _require_execution_authorization_consistency(
    *,
    authorization: dict[str, Any],
    decision: dict[str, Any],
    missing_source_readiness: dict[str, Any],
    label: str,
) -> None:
    summary = _dict(authorization.get("summary"))
    boundaries = _dict(authorization.get("operation_boundaries"))
    authorized_targets = [
        _dict(row) for row in _list(authorization.get("authorized_targets"))
    ]
    approval_required_repos = {
        str(row.get("github_repo"))
        for row in _list(decision.get("decisions"))
        if _dict(row).get("approval_required") is True
    }
    authorized_repos = {
        str(row.get("github_repo"))
        for row in authorized_targets
        if row.get("github_repo")
    }
    if authorized_repos != approval_required_repos:
        raise ValueError(
            f"{label}: authorized targets must match approval-required targets"
        )
    if _int(summary.get("authorized_target_count")) != len(authorized_targets):
        raise ValueError(f"{label}: authorized target count must match targets")
    if _int(summary.get("authorization_received_count")) < 1:
        raise ValueError(f"{label}: authorization_received_count must be >= 1")

    required_true_flags = {
        "repo_creation_authorized",
        "visibility_change_authorized",
        "refs_sync_authorized",
        "workflow_trigger_authorized",
    }
    missing_true_flags = sorted(
        flag for flag in required_true_flags if summary.get(flag) is not True
    )
    if missing_true_flags:
        raise ValueError(
            f"{label}: controlled execution flags must be true: {missing_true_flags}"
        )

    required_boundary_true_flags = {
        "github_api_write_allowed",
        "repo_creation_allowed",
        "visibility_change_allowed",
        "refs_sync_allowed",
        "workflow_trigger_allowed",
    }
    missing_boundary_true_flags = sorted(
        flag
        for flag in required_boundary_true_flags
        if boundaries.get(flag) is not True
    )
    if missing_boundary_true_flags:
        raise ValueError(
            f"{label}: controlled operation boundaries must be true: {missing_boundary_true_flags}"
        )

    forbidden_true_flags = {
        "github_primary_switch_authorized",
        "workflow_modification_authorized",
        "delete_refs_authorized",
        "force_push_authorized",
        "public_repo_allowed",
        "public_visibility_allowed",
        "secret_value_collection_allowed",
        "private_clone_url_collection_allowed",
        "credential_value_collection_allowed",
        "raw_payload_storage_allowed",
        "write_performed",
        "repo_creation_performed",
        "visibility_change_performed",
        "refs_sync_performed",
        "workflow_trigger_performed",
    }
    enabled = sorted(
        flag for flag in forbidden_true_flags if summary.get(flag) is not False
    )
    forbidden_boundary_true_flags = {
        "workflow_modification_allowed",
        "github_primary_switch_allowed",
        "delete_refs_allowed",
        "force_push_allowed",
        "secret_value_collection_allowed",
        "private_clone_url_collection_allowed",
        "credential_value_collection_allowed",
        "raw_payload_storage_allowed",
    }
    enabled.extend(
        sorted(
            flag
            for flag in forbidden_boundary_true_flags
            if boundaries.get(flag) is not False
        )
    )
    if enabled:
        raise ValueError(f"{label}: forbidden authorization flags enabled: {enabled}")

    required_still_forbidden = {
        "secret_value",
        "token_value",
        "private_clone_url_credential",
        "repo_archive",
        "git_object_pack",
        "force_push",
        "delete_refs",
        "github_primary_switch",
    }
    missing_forbidden = sorted(
        required_still_forbidden - set(_strings(authorization.get("still_forbidden")))
    )
    if missing_forbidden:
        raise ValueError(
            f"{label}: still_forbidden missing critical boundaries: {missing_forbidden}"
        )

    missing_targets = {
        str(row.get("github_repo"))
        for row in _list(missing_source_readiness.get("targets"))
        if _dict(row).get("github_repo")
    }
    create_authorized_repos = {
        str(row.get("github_repo"))
        for row in authorized_targets
        if row.get("create_private_repo_authorized") is True
    }
    refs_authorized_missing_repos = {
        str(row.get("github_repo"))
        for row in authorized_targets
        if row.get("github_repo") in missing_targets
        and row.get("refs_sync_authorized") is True
    }
    if create_authorized_repos != missing_targets:
        raise ValueError(
            f"{label}: create authorization must match missing-source targets"
        )
    if refs_authorized_missing_repos != missing_targets:
        raise ValueError(
            f"{label}: refs sync authorization must cover missing-source targets"
        )
    if _int(
        summary.get("github_missing_target_create_private_repo_authorized_count")
    ) != len(missing_targets):
        raise ValueError(f"{label}: missing target create authorization count drift")
    if _int(summary.get("github_missing_target_refs_sync_authorized_count")) != len(
        missing_targets
    ):
        raise ValueError(f"{label}: missing target refs authorization count drift")


def _require_controlled_execution_preflight_consistency(
    *,
    preflight: dict[str, Any],
    missing_source_readiness: dict[str, Any],
    label: str,
) -> None:
    summary = _dict(preflight.get("summary"))
    boundaries = _dict(preflight.get("operation_boundaries"))
    targets = [_dict(row) for row in _list(preflight.get("targets"))]
    missing_targets = {
        str(row.get("github_repo"))
        for row in _list(missing_source_readiness.get("targets"))
        if _dict(row).get("github_repo")
    }
    preflight_targets = {
        str(row.get("github_repo")) for row in targets if row.get("github_repo")
    }
    if preflight_targets != missing_targets:
        raise ValueError(f"{label}: preflight targets must match missing targets")
    if _int(summary.get("authorized_missing_target_count")) != len(targets):
        raise ValueError(f"{label}: authorized missing target count must match targets")

    github_404_count = sum(
        1 for row in targets if row.get("github_readback_status") == "api_404_not_found"
    )
    github_forbidden_count = sum(
        1
        for row in targets
        if row.get("github_readback_status") == "api_403_account_suspended"
    )
    source_ready_count = sum(
        1 for row in targets if row.get("source_preflight_ready") is True
    )
    create_ready_count = sum(
        1 for row in targets if row.get("create_private_repo_apply_ready") is True
    )
    refs_ready_count = sum(
        1 for row in targets if row.get("refs_sync_apply_ready") is True
    )
    blocked_count = sum(
        1 for row in targets if row.get("controlled_apply_ready") is not True
    )
    if (
        _int(summary.get("github_connector_missing_target_404_count"))
        != github_404_count
    ):
        raise ValueError(f"{label}: GitHub 404 count must match targets")
    if _int(summary.get("github_api_forbidden_count")) != github_forbidden_count + 1:
        raise ValueError(f"{label}: GitHub forbidden count must match checked repos")
    if _int(summary.get("source_preflight_ready_count")) != source_ready_count:
        raise ValueError(f"{label}: source preflight ready count must match targets")
    if _int(summary.get("create_private_repo_apply_ready_count")) != create_ready_count:
        raise ValueError(f"{label}: create apply ready count must match targets")
    if _int(summary.get("refs_sync_apply_ready_count")) != refs_ready_count:
        raise ValueError(f"{label}: refs sync ready count must match targets")
    if _int(summary.get("blocked_preflight_target_count")) != blocked_count:
        raise ValueError(f"{label}: blocked preflight count must match targets")

    false_summary_flags = {
        "local_gh_auth_ready",
        "github_connector_repo_creation_tool_available",
        "github_create_repo_channel_ready",
        "github_refs_sync_channel_ready",
        "write_performed",
        "repo_creation_performed",
        "visibility_change_performed",
        "refs_sync_performed",
        "workflow_trigger_performed",
        "secret_values_collected",
        "private_clone_urls_collected",
    }
    enabled = sorted(
        flag for flag in false_summary_flags if summary.get(flag) is not False
    )
    false_boundary_flags = {
        "github_create_repo_channel_ready",
        "github_refs_sync_channel_ready",
        "controlled_apply_allowed",
        "repo_creation_allowed",
        "visibility_change_allowed",
        "refs_sync_allowed",
        "workflow_trigger_allowed",
        "force_push_allowed",
        "delete_refs_allowed",
        "public_visibility_allowed",
        "github_primary_switch_allowed",
        "secret_value_collection_allowed",
        "private_clone_url_collection_allowed",
        "raw_payload_storage_allowed",
    }
    enabled.extend(
        sorted(
            flag for flag in false_boundary_flags if boundaries.get(flag) is not False
        )
    )
    if enabled:
        raise ValueError(
            f"{label}: preflight must not claim write readiness: {enabled}"
        )

    required_forbidden = {
        "secret_value",
        "token_value",
        "private_clone_url_credential",
        "repo_archive",
        "git_object_pack",
        "force_push",
        "delete_refs",
        "github_primary_switch",
        "public_visibility",
    }
    missing_forbidden = sorted(
        required_forbidden - set(_strings(preflight.get("still_forbidden")))
    )
    if missing_forbidden:
        raise ValueError(
            f"{label}: still_forbidden missing critical boundaries: {missing_forbidden}"
        )


def _require_operator_unblock_governance_closure_consistency(
    *, payload: dict[str, Any], label: str
) -> None:
    summary = _dict(payload.get("summary"))
    boundaries = _dict(payload.get("operation_boundaries"))
    mcp_packets = _list(payload.get("mcp_evidence_packets"))
    rag_refs = _list(payload.get("rag_evidence_refs"))
    km_items = [_dict(row) for row in _list(payload.get("km_writeback_items"))]
    playbook_items = [
        _dict(row) for row in _list(payload.get("playbook_writeback_items"))
    ]
    timeline_items = [_dict(row) for row in _list(payload.get("timeline_log_items"))]
    logbook_entries = _list(payload.get("logbook_entries"))

    count_pairs = {
        "mcp_evidence_packet_count": len(mcp_packets),
        "rag_evidence_ref_count": len(rag_refs),
        "km_writeback_item_count": len(km_items),
        "km_writeback_ready_count": sum(
            1 for row in km_items if row.get("ready_for_writeback") is True
        ),
        "playbook_writeback_item_count": len(playbook_items),
        "playbook_writeback_ready_count": sum(
            1 for row in playbook_items if row.get("ready_for_writeback") is True
        ),
        "timeline_log_item_count": len(timeline_items),
        "timeline_log_ready_count": sum(
            1 for row in timeline_items if row.get("ready_for_writeback") is True
        ),
        "logbook_entry_count": len(logbook_entries),
    }
    mismatched = sorted(
        key for key, expected in count_pairs.items() if _int(summary.get(key)) != expected
    )
    if mismatched:
        raise ValueError(f"{label}: governance writeback count drift: {mismatched}")

    false_summary_flags = {
        "github_write_performed",
        "gh_cli_called",
        "github_api_called",
        "github_repo_creation_performed",
        "github_refs_sync_performed",
        "github_visibility_change_performed",
        "secret_values_collected",
        "raw_session_or_sqlite_read",
        "runtime_write_performed",
        "host_or_k8s_write_performed",
    }
    enabled = sorted(
        flag for flag in false_summary_flags if summary.get(flag) is not False
    )
    false_boundary_flags = {
        "github_app_connector_mcp_allowed",
        "gh_cli_allowed",
        "github_api_allowed",
        "github_actions_allowed",
        "github_repo_creation_allowed",
        "github_refs_sync_allowed",
        "github_visibility_change_allowed",
        "github_primary_switch_allowed",
        "force_push_allowed",
        "delete_refs_allowed",
        "secret_value_collection_allowed",
        "private_clone_url_collection_allowed",
        "raw_session_read_allowed",
        "sqlite_read_allowed",
        "runtime_write_allowed",
        "host_or_k8s_write_allowed",
    }
    enabled.extend(
        sorted(
            flag for flag in false_boundary_flags if boundaries.get(flag) is not False
        )
    )
    if enabled:
        raise ValueError(
            f"{label}: governance closure must stay local-only: {enabled}"
        )


def _require_owner_response_boundaries(payload: dict[str, Any], label: str) -> None:
    if payload.get("runtime_execution_authorized") is not False:
        raise ValueError(f"{label}: runtime_execution_authorized must be false")
    summary = _dict(payload.get("summary"))
    false_flags = {
        "repo_creation_authorized",
        "visibility_change_authorized",
        "refs_sync_authorized",
        "github_primary_switch_authorized",
        "secret_value_collection_allowed",
        "action_buttons_allowed",
        "target_owner_request_dispatch_authorized",
        "not_found_or_private_as_absent_allowed",
        "repo_creation_allowed_without_owner_response",
        "visibility_change_allowed_without_owner_response",
    }
    enabled = sorted(flag for flag in false_flags if summary.get(flag) is not False)
    if enabled:
        raise ValueError(
            f"{label}: owner response boundary flags must remain false: {enabled}"
        )
    _require_owner_response_intake_consistency(payload, label)


def _require_owner_response_intake_consistency(
    payload: dict[str, Any], label: str
) -> None:
    packet = _dict(payload.get("owner_response_request_packet"))
    templates = [_dict(row) for row in _list(payload.get("response_templates"))]
    collection_checks = [
        _dict(row) for row in _list(payload.get("owner_response_collection_checks"))
    ]
    preflight_checks = [
        _dict(row) for row in _list(payload.get("intake_preflight_checks"))
    ]
    acceptance_checks = [_dict(row) for row in _list(payload.get("acceptance_checks"))]
    redaction_examples = [
        _dict(row) for row in _list(payload.get("owner_response_redaction_examples"))
    ]
    summary = _dict(payload.get("summary"))

    if (
        packet.get("execution_authorized") is not False
        or packet.get("not_approval") is not True
    ):
        raise ValueError(
            f"{label}: owner response request packet must remain non-executing"
        )

    requested_template_ids = _strings(packet.get("requested_template_ids"))
    if _int(packet.get("required_response_item_count")) != len(requested_template_ids):
        raise ValueError(
            f"{label}: required response item count must match requested templates"
        )
    if _int(summary.get("response_template_count")) != len(templates):
        raise ValueError(f"{label}: response template count must match templates")
    if _int(summary.get("owner_response_collection_check_count")) != len(
        collection_checks
    ):
        raise ValueError(f"{label}: collection check count must match checks")
    if _int(summary.get("intake_preflight_check_count")) != len(preflight_checks):
        raise ValueError(f"{label}: intake preflight check count must match checks")
    if _int(summary.get("acceptance_check_count")) != len(acceptance_checks):
        raise ValueError(f"{label}: acceptance check count must match checks")
    if _int(summary.get("owner_response_redaction_example_count")) != len(
        redaction_examples
    ):
        raise ValueError(f"{label}: redaction example count must match examples")

    template_ids = {
        str(row.get("template_id")) for row in templates if row.get("template_id")
    }
    missing_templates = sorted(set(requested_template_ids) - template_ids)
    if missing_templates:
        raise ValueError(
            f"{label}: requested templates missing from response templates: {missing_templates}"
        )

    executable_rows = [
        str(
            row.get("template_id")
            or row.get("check_id")
            or row.get("example_id")
            or "unknown"
        )
        for row in [
            *templates,
            *collection_checks,
            *preflight_checks,
            *acceptance_checks,
            *redaction_examples,
        ]
        if row.get("execution_authorized") is not False
    ]
    if executable_rows:
        raise ValueError(
            f"{label}: owner response intake rows must remain non-executing: {executable_rows}"
        )

    raw_payload_examples = [
        str(row.get("example_id") or "unknown")
        for row in redaction_examples
        if row.get("stored_raw_payload_allowed") is not False
    ]
    if raw_payload_examples:
        raise ValueError(
            f"{label}: redaction examples must not allow raw payload storage: {raw_payload_examples}"
        )

    required_forbidden_payloads = {
        "token_value",
        "secret_value",
        "private_clone_url_credential",
        "repo_archive",
        "git_object_pack",
    }
    missing_forbidden_payloads = sorted(
        required_forbidden_payloads - set(_strings(packet.get("forbidden_payloads")))
    )
    if missing_forbidden_payloads:
        raise ValueError(
            f"{label}: forbidden payloads missing safe credential blockers: {missing_forbidden_payloads}"
        )


def _owner_response_intake_readiness(owner_response: dict[str, Any]) -> dict[str, Any]:
    summary = _dict(owner_response.get("summary"))
    packet = _dict(owner_response.get("owner_response_request_packet"))
    requested_template_ids = _strings(packet.get("requested_template_ids"))
    response_templates = [
        _owner_response_template_summary(row)
        for row in _list(owner_response.get("response_templates"))
    ]
    collection_checks = [
        _intake_check_summary(row)
        for row in _list(owner_response.get("owner_response_collection_checks"))
    ]
    preflight_checks = [
        _intake_check_summary(row)
        for row in _list(owner_response.get("intake_preflight_checks"))
    ]
    acceptance_checks = [
        _intake_check_summary(row)
        for row in _list(owner_response.get("acceptance_checks"))
    ]
    request_ready = (
        packet.get("execution_authorized") is False
        and packet.get("not_approval") is True
        and bool(requested_template_ids)
        and len(requested_template_ids) == len(response_templates)
        and _int(summary.get("target_owner_handoff_package_ready")) == 1
    )
    return {
        "status": "ready_to_collect_read_only_owner_response_not_authorization"
        if request_ready
        else "blocked_owner_response_request_packet_incomplete",
        "request_ready": request_ready,
        "request_id": str(packet.get("request_id") or ""),
        "display_status": str(packet.get("display_status") or ""),
        "requested_packet": str(packet.get("requested_packet") or ""),
        "required_response_item_count": _int(
            packet.get("required_response_item_count")
        ),
        "requested_template_count": len(requested_template_ids),
        "requested_template_ids": requested_template_ids,
        "response_template_count": len(response_templates),
        "response_templates": response_templates,
        "allowed_response_field_count": len(
            _strings(packet.get("allowed_response_fields"))
        ),
        "allowed_response_fields": _strings(packet.get("allowed_response_fields")),
        "evidence_ref_rules": _strings(packet.get("evidence_ref_rules")),
        "forbidden_payload_count": len(_strings(packet.get("forbidden_payloads"))),
        "forbidden_payloads": _strings(packet.get("forbidden_payloads")),
        "allowed_submission_modes": _strings(packet.get("allowed_submission_modes")),
        "collection_check_count": len(collection_checks),
        "collection_checks": collection_checks,
        "intake_preflight_check_count": len(preflight_checks),
        "intake_preflight_checks": preflight_checks,
        "acceptance_check_count": len(acceptance_checks),
        "acceptance_checks": acceptance_checks,
        "still_forbidden": _strings(packet.get("still_forbidden")),
        "received_response_count": _int(summary.get("received_response_count")),
        "accepted_response_count": _int(summary.get("accepted_response_count")),
        "rejected_response_count": _int(summary.get("rejected_response_count")),
        "target_owner_request_dispatch_authorized": False,
        "action_buttons_allowed": False,
        "execution_authorized": False,
        "not_approval": True,
    }


def _execution_authorization_summary(
    execution_authorization: dict[str, Any],
) -> dict[str, Any]:
    summary = _dict(execution_authorization.get("summary"))
    boundaries = _dict(execution_authorization.get("operation_boundaries"))
    authorization_present = bool(execution_authorization)
    repo_creation_authorized = summary.get("repo_creation_authorized") is True
    visibility_change_authorized = summary.get("visibility_change_authorized") is True
    refs_sync_authorized = summary.get("refs_sync_authorized") is True
    workflow_trigger_authorized = summary.get("workflow_trigger_authorized") is True
    return {
        "authorization_present": authorization_present,
        "status": str(
            execution_authorization.get("status")
            or "owner_execution_authorization_not_received"
        ),
        "mode": str(execution_authorization.get("mode") or ""),
        "authorization_source": str(
            execution_authorization.get("authorization_source") or ""
        ),
        "authorization_received_count": _int(
            summary.get("authorization_received_count")
        ),
        "authorized_target_count": _int(summary.get("authorized_target_count")),
        "github_missing_target_create_private_repo_authorized_count": _int(
            summary.get("github_missing_target_create_private_repo_authorized_count")
        ),
        "github_missing_target_refs_sync_authorized_count": _int(
            summary.get("github_missing_target_refs_sync_authorized_count")
        ),
        "github_api_write_allowed": boundaries.get("github_api_write_allowed") is True,
        "repo_creation_authorized": repo_creation_authorized,
        "visibility_change_authorized": visibility_change_authorized,
        "refs_sync_authorized": refs_sync_authorized,
        "workflow_trigger_authorized": workflow_trigger_authorized,
        "github_primary_switch_authorized": False,
        "not_found_or_private_as_absent_allowed": repo_creation_authorized
        and visibility_change_authorized
        and refs_sync_authorized,
    }


def _controlled_execution_preflight_readiness(
    *,
    payload: dict[str, Any],
    targets: list[dict[str, Any]],
    authorization_summary: dict[str, Any],
) -> dict[str, Any]:
    summary = _dict(payload.get("summary"))
    boundaries = _dict(payload.get("operation_boundaries"))
    preflight_targets = [
        _controlled_execution_target_summary(row)
        for row in _list(payload.get("targets"))
    ]
    blocked_count = _int(summary.get("blocked_preflight_target_count"))
    controlled_apply_ready_count = sum(
        1 for row in preflight_targets if row["controlled_apply_ready"]
    )
    create_channel_ready = summary.get("github_create_repo_channel_ready") is True
    refs_channel_ready = summary.get("github_refs_sync_channel_ready") is True
    write_channel_ready = create_channel_ready and refs_channel_ready
    github_account_status = str(summary.get("github_account_status") or "unknown")
    github_account_suspended = summary.get("github_account_suspended") is True
    github_api_forbidden_count = _int(summary.get("github_api_forbidden_count"))
    preflight_ready = (
        bool(preflight_targets)
        and authorization_summary["authorization_present"] is True
        and authorization_summary["repo_creation_authorized"] is True
        and authorization_summary["refs_sync_authorized"] is True
        and write_channel_ready
        and blocked_count == 0
    )
    missing_target_repos = {
        str(row.get("github_repo"))
        for row in targets
        if row.get("missing_target_source_resolution_status")
    }
    evaluated_repos = {
        str(row.get("github_repo"))
        for row in preflight_targets
        if row.get("github_repo")
    }
    operator_unblock = _github_write_channel_operator_unblock(
        github_account_status=github_account_status,
        github_account_suspended=github_account_suspended,
        github_api_forbidden_count=github_api_forbidden_count,
        github_write_channel_ready=write_channel_ready,
    )
    return {
        "schema_version": str(
            payload.get("schema_version")
            or "missing_github_target_controlled_execution_preflight_v1"
        ),
        "generated_at": str(payload.get("generated_at") or ""),
        "status": str(
            payload.get("status")
            or "blocked_github_controlled_execution_preflight_missing"
        ),
        "mode": str(
            payload.get("mode") or "controlled_apply_preflight_missing_no_github_write"
        ),
        "authorization_source": str(payload.get("authorization_source") or ""),
        "preflight_ready": preflight_ready,
        "authorization_ready": authorization_summary["authorization_present"] is True
        and authorization_summary["repo_creation_authorized"] is True
        and authorization_summary["refs_sync_authorized"] is True,
        "github_write_channel_ready": write_channel_ready,
        "github_account_status": github_account_status,
        "github_account_suspended": github_account_suspended,
        "github_api_forbidden_count": github_api_forbidden_count,
        "github_create_repo_channel_ready": create_channel_ready,
        "github_refs_sync_channel_ready": refs_channel_ready,
        "github_connector_repo_creation_tool_available": summary.get(
            "github_connector_repo_creation_tool_available"
        )
        is True,
        "github_connector_refs_write_tool_available": summary.get(
            "github_connector_refs_write_tool_available"
        )
        is True,
        "local_gh_auth_ready": summary.get("local_gh_auth_ready") is True,
        "source_preflight_ready_count": _int(
            summary.get("source_preflight_ready_count")
        ),
        "controlled_apply_ready_count": controlled_apply_ready_count,
        "create_private_repo_apply_ready_count": _int(
            summary.get("create_private_repo_apply_ready_count")
        ),
        "refs_sync_apply_ready_count": _int(summary.get("refs_sync_apply_ready_count")),
        "blocked_preflight_target_count": blocked_count,
        "github_connector_missing_target_404_count": _int(
            summary.get("github_connector_missing_target_404_count")
        ),
        "missing_target_count": len(missing_target_repos),
        "evaluated_missing_target_count": len(evaluated_repos & missing_target_repos),
        "tool_channel_readback": _dict(payload.get("tool_channel_readback")),
        "required_preflight_checks": _strings(payload.get("required_preflight_checks")),
        "rollback_plan": _dict(payload.get("rollback_plan")),
        "post_apply_verifiers": _strings(payload.get("post_apply_verifiers")),
        "operator_unblock_required": operator_unblock["required"],
        "operator_unblock_status": operator_unblock["status"],
        "operator_unblock": operator_unblock,
        "operation_boundaries": {
            "read_only_api_allowed": boundaries.get("read_only_api_allowed") is True,
            "github_api_write_allowed_by_authorization": boundaries.get(
                "github_api_write_allowed_by_authorization"
            )
            is True,
            "github_create_repo_channel_ready": create_channel_ready,
            "github_refs_sync_channel_ready": refs_channel_ready,
            "controlled_apply_allowed": preflight_ready,
            "repo_creation_allowed": preflight_ready,
            "visibility_change_allowed": preflight_ready,
            "refs_sync_allowed": preflight_ready,
            "workflow_trigger_allowed": preflight_ready,
            "force_push_allowed": False,
            "delete_refs_allowed": False,
            "public_visibility_allowed": False,
            "github_primary_switch_allowed": False,
            "secret_value_collection_allowed": False,
            "private_clone_url_collection_allowed": False,
            "raw_payload_storage_allowed": False,
        },
        "targets": preflight_targets,
        "still_forbidden": _strings(payload.get("still_forbidden")),
    }


def _github_write_channel_operator_unblock(
    *,
    github_account_status: str,
    github_account_suspended: bool,
    github_api_forbidden_count: int,
    github_write_channel_ready: bool,
) -> dict[str, Any]:
    required = not github_write_channel_ready
    if github_account_suspended:
        status = "github_account_suspended_external_action_required"
    elif required:
        status = "github_write_channel_reauthentication_or_namespace_required"
    else:
        status = "github_write_channel_ready_no_operator_action"

    return {
        "required": required,
        "status": status,
        "github_account_status": github_account_status,
        "github_account_suspended": github_account_suspended,
        "github_api_forbidden_count": github_api_forbidden_count,
        "required_actions": _GITHUB_OPERATOR_UNBLOCK_ACTIONS if required else [],
        "recheck_commands": _GITHUB_WRITE_CHANNEL_RECHECK_COMMANDS if required else [],
        "still_forbidden": _GITHUB_OPERATOR_STILL_FORBIDDEN,
        "safe_handoff": (
            "GitHub owner must restore the suspended account or provide a writable "
            "private GitHub namespace. Do not share tokens, cookies, private keys, "
            "authorization headers, or private clone URLs."
        )
        if required
        else "GitHub write channel is ready for controlled apply preflight.",
    }


def _github_operator_unblock_internal_governance_writeback(
    *,
    payload: dict[str, Any],
    controlled_preflight: dict[str, Any],
) -> dict[str, Any]:
    if not payload:
        return {
            "schema_version": "missing_github_operator_unblock_governance_closure_v1",
            "generated_at": "",
            "status": "missing_operator_unblock_governance_closure_snapshot",
            "ready": False,
            "mcp_evidence_packet_count": 0,
            "rag_evidence_ref_count": 0,
            "km_writeback_ready_count": 0,
            "playbook_writeback_ready_count": 0,
            "timeline_log_ready_count": 0,
            "logbook_entry_count": 0,
            "github_account_status": controlled_preflight.get(
                "github_account_status"
            ),
            "github_account_suspended": controlled_preflight.get(
                "github_account_suspended"
            )
            is True,
            "github_write_channel_ready": controlled_preflight.get(
                "github_write_channel_ready"
            )
            is True,
            "github_write_performed": False,
            "secret_values_collected": False,
            "source_refs": {},
            "mcp_evidence_packets": [],
            "rag_evidence_refs": [],
            "km_writeback_items": [],
            "playbook_writeback_items": [],
            "timeline_log_items": [],
            "logbook_entries": [],
            "operation_boundaries": {},
            "still_forbidden": [],
            "next_action": "add_committed_operator_unblock_governance_closure_snapshot",
        }

    summary = _dict(payload.get("summary"))
    boundaries = _dict(payload.get("operation_boundaries"))
    return {
        "schema_version": str(payload.get("schema_version") or ""),
        "generated_at": str(payload.get("generated_at") or ""),
        "status": str(payload.get("status") or ""),
        "ready": summary.get("governance_writeback_ready") is True,
        "mcp_evidence_packet_count": _int(
            summary.get("mcp_evidence_packet_count")
        ),
        "rag_evidence_ref_count": _int(summary.get("rag_evidence_ref_count")),
        "km_writeback_ready_count": _int(
            summary.get("km_writeback_ready_count")
        ),
        "playbook_writeback_ready_count": _int(
            summary.get("playbook_writeback_ready_count")
        ),
        "timeline_log_ready_count": _int(
            summary.get("timeline_log_ready_count")
        ),
        "logbook_entry_count": _int(summary.get("logbook_entry_count")),
        "github_account_status": str(
            summary.get("github_account_status")
            or controlled_preflight.get("github_account_status")
            or "unknown"
        ),
        "github_account_suspended": summary.get("github_account_suspended") is True,
        "github_write_channel_ready": summary.get("github_write_channel_ready")
        is True,
        "source_preflight_ready_count": _int(
            summary.get("source_preflight_ready_count")
        ),
        "controlled_apply_ready_count": _int(
            summary.get("controlled_apply_ready_count")
        ),
        "blocked_preflight_target_count": _int(
            summary.get("blocked_preflight_target_count")
        ),
        "github_write_performed": summary.get("github_write_performed") is True,
        "gh_cli_called": summary.get("gh_cli_called") is True,
        "github_api_called": summary.get("github_api_called") is True,
        "secret_values_collected": summary.get("secret_values_collected") is True,
        "source_refs": _dict(payload.get("source_refs")),
        "mcp_evidence_packets": _list(payload.get("mcp_evidence_packets")),
        "rag_evidence_refs": _list(payload.get("rag_evidence_refs")),
        "km_writeback_items": _list(payload.get("km_writeback_items")),
        "playbook_writeback_items": _list(payload.get("playbook_writeback_items")),
        "timeline_log_items": _list(payload.get("timeline_log_items")),
        "logbook_entries": _list(payload.get("logbook_entries")),
        "operation_boundaries": {
            "local_source_snapshot_allowed": boundaries.get(
                "local_source_snapshot_allowed"
            )
            is True,
            "github_app_connector_mcp_allowed": False,
            "gh_cli_allowed": False,
            "github_api_allowed": False,
            "github_actions_allowed": False,
            "github_repo_creation_allowed": False,
            "github_refs_sync_allowed": False,
            "github_visibility_change_allowed": False,
            "github_primary_switch_allowed": False,
            "force_push_allowed": False,
            "delete_refs_allowed": False,
            "secret_value_collection_allowed": False,
            "private_clone_url_collection_allowed": False,
            "raw_session_read_allowed": False,
            "sqlite_read_allowed": False,
            "runtime_write_allowed": False,
            "host_or_k8s_write_allowed": False,
        },
        "still_forbidden": _strings(payload.get("still_forbidden")),
        "next_action": str(payload.get("next_action") or ""),
    }


def _controlled_execution_target_summary(value: Any) -> dict[str, Any]:
    row = _dict(value)
    return {
        "github_repo": str(row.get("github_repo") or ""),
        "github_readback_status": str(row.get("github_readback_status") or ""),
        "target_selector": str(row.get("target_selector") or ""),
        "source_resolution_status": str(row.get("source_resolution_status") or ""),
        "source_candidate_type": str(row.get("source_candidate_type") or ""),
        "canonical_source_ref": str(row.get("canonical_source_ref") or ""),
        "canonical_source_sha": str(row.get("canonical_source_sha") or ""),
        "source_probe_status": str(row.get("source_probe_status") or ""),
        "source_warnings": _strings(row.get("source_warnings")),
        "source_preflight_ready": row.get("source_preflight_ready") is True,
        "canonical_source_ready": row.get("canonical_source_ready") is True,
        "github_collision_preflight_ready": row.get("github_collision_preflight_ready")
        is True,
        "create_private_repo_apply_ready": row.get("create_private_repo_apply_ready")
        is True,
        "refs_sync_apply_ready": row.get("refs_sync_apply_ready") is True,
        "controlled_apply_ready": row.get("controlled_apply_ready") is True,
        "blockers": _strings(row.get("blockers")),
        "next_action": str(row.get("next_action") or ""),
    }


def _safe_credential_evidence_intake_readiness(
    *,
    owner_response: dict[str, Any],
    required_target_count: int,
) -> dict[str, Any]:
    summary = _dict(owner_response.get("summary"))
    packet = _dict(owner_response.get("owner_response_request_packet"))
    evidence_ref_rules = _strings(packet.get("evidence_ref_rules"))
    redaction_examples = [
        _redaction_example_summary(row)
        for row in _list(owner_response.get("owner_response_redaction_examples"))
    ]
    forbidden_payloads = _strings(packet.get("forbidden_payloads"))
    checks = [
        *[
            _dict(row)
            for row in _list(owner_response.get("owner_response_collection_checks"))
        ],
        *[_dict(row) for row in _list(owner_response.get("intake_preflight_checks"))],
        *[_dict(row) for row in _list(owner_response.get("acceptance_checks"))],
    ]
    quarantine_lanes = sorted(
        {
            str(row.get("failure_lane"))
            for row in checks
            if str(row.get("failure_lane") or "").startswith("quarantine")
        }
    )
    accepted_evidence_count = 0
    required_redacted_evidence_ref_count = (
        required_target_count - accepted_evidence_count
    )
    required_forbidden_payloads = {
        "token_value",
        "secret_value",
        "private_clone_url_credential",
        "repo_archive",
        "git_object_pack",
    }
    intake_ready = (
        packet.get("execution_authorized") is False
        and packet.get("not_approval") is True
        and bool(evidence_ref_rules)
        and bool(redaction_examples)
        and _int(summary.get("owner_response_redaction_example_count"))
        == len(redaction_examples)
        and required_forbidden_payloads.issubset(set(forbidden_payloads))
    )

    return {
        "status": "ready_to_collect_redacted_evidence_refs_not_credentials"
        if intake_ready
        else "blocked_safe_credential_evidence_intake_contract_incomplete",
        "intake_ready": intake_ready,
        "required_target_count": required_target_count,
        "accepted_evidence_count": accepted_evidence_count,
        "required_redacted_evidence_ref_count": required_redacted_evidence_ref_count,
        "allowed_evidence_ref_types": [
            "repo_path",
            "snapshot_path",
            "redacted_metadata_pointer",
        ],
        "evidence_ref_rule_count": len(evidence_ref_rules),
        "evidence_ref_rules": evidence_ref_rules,
        "redaction_example_count": len(redaction_examples),
        "redaction_examples": redaction_examples,
        "forbidden_payload_count": len(forbidden_payloads),
        "forbidden_payloads": forbidden_payloads,
        "quarantine_lane_count": len(quarantine_lanes),
        "quarantine_lanes": quarantine_lanes,
        "allowed_submission_modes": _strings(packet.get("allowed_submission_modes")),
        "reviewer_validation_endpoint": _SAFE_CREDENTIAL_REVIEW_ENDPOINT,
        "reviewer_validation_mode": _SAFE_CREDENTIAL_REVIEW_MODE,
        "reviewer_validation_ready": intake_ready,
        "reviewer_validation_required_field_count": len(
            _SAFE_CREDENTIAL_REVIEW_REQUIRED_FIELDS
        ),
        "reviewer_validation_required_fields": list(
            _SAFE_CREDENTIAL_REVIEW_REQUIRED_FIELDS
        ),
        "reviewer_validation_allowed_decisions": [
            _SAFE_CREDENTIAL_REVIEW_ACCEPT_DECISION
        ],
        "reviewer_validation_no_persist": True,
        "stored_raw_payload_allowed": False,
        "secret_value_collection_allowed": False,
        "private_clone_url_collection_allowed": False,
        "credential_value_collection_allowed": False,
        "target_owner_request_dispatch_authorized": False,
        "action_buttons_allowed": False,
        "execution_authorized": False,
        "not_approval": True,
    }


def _redaction_example_summary(value: Any) -> dict[str, Any]:
    row = _dict(value)
    return {
        "example_id": str(row.get("example_id") or ""),
        "display_order": _int(row.get("display_order")),
        "example_status": str(row.get("example_status") or ""),
        "category": str(row.get("category") or ""),
        "safe_response_shape": _strings(row.get("safe_response_shape")),
        "required_redactions": _strings(row.get("required_redactions")),
        "forbidden_raw_values": _strings(row.get("forbidden_raw_values")),
        "stored_raw_payload_allowed": False,
        "execution_authorized": False,
        "not_approval": row.get("not_approval") is True,
    }


def _owner_response_template_summary(value: Any) -> dict[str, Any]:
    row = _dict(value)
    return {
        "template_id": str(row.get("template_id") or ""),
        "github_repo": str(row.get("github_repo") or ""),
        "source_key": str(row.get("source_key") or ""),
        "target_state": str(row.get("target_state") or ""),
        "risk": str(row.get("risk") or ""),
        "requested_owner_decision": str(row.get("requested_owner_decision") or ""),
        "required_owner_fields": _strings(row.get("required_owner_fields")),
        "acceptable_decisions": _strings(row.get("acceptable_decisions")),
        "minimum_evidence_refs": _strings(row.get("minimum_evidence_refs")),
        "execution_authorized": False,
    }


def _intake_check_summary(value: Any) -> dict[str, Any]:
    row = _dict(value)
    return {
        "check_id": str(row.get("check_id") or ""),
        "title": str(row.get("title") or ""),
        "required": row.get("required") is True,
        "pass_condition": str(row.get("pass_condition") or ""),
        "failure_lane": str(row.get("failure_lane") or ""),
        "awooop_display": str(row.get("awooop_display") or ""),
        "execution_authorized": False,
        "not_approval": row.get("not_approval") is True,
    }


def _generated_at(owner_response: dict[str, Any]) -> str:
    if owner_response.get("generated_at"):
        return str(owner_response["generated_at"])
    if owner_response.get("date"):
        return f"{owner_response['date']}T00:00:00+08:00"
    return ""


def _acceptance_requirements(owner_response: dict[str, Any]) -> list[str]:
    packet = _dict(owner_response.get("target_owner_handoff_packet"))
    requirements = _strings(packet.get("required_response_fields"))
    return requirements or [
        "owner_role_or_team",
        "decision",
        "decision_reason",
        "affected_scope",
        "redacted_evidence_refs",
        "followup_owner",
        "rollback_owner",
        "maintenance_window",
        "validation_plan",
    ]


def _rejection_rules(owner_response: dict[str, Any]) -> list[str]:
    packet = _dict(owner_response.get("owner_response_request_packet"))
    rules = _strings(packet.get("forbidden_payloads"))
    return rules or [
        "token_value",
        "secret_value",
        "private_key",
        "private_clone_url_credential",
        "repo_creation_command",
        "visibility_change_command",
        "refs_sync_or_delete_request",
    ]


def _has_response_value(value: Any) -> bool:
    if isinstance(value, str):
        return bool(value.strip())
    if isinstance(value, list):
        return any(_has_response_value(item) for item in value)
    return value is not None


def _response_strings(value: Any) -> list[str]:
    if isinstance(value, str):
        return [value] if value.strip() else []
    if isinstance(value, list):
        return [str(item) for item in value if str(item).strip()]
    return []


def _forbidden_payload_hits(
    value: Any,
    *,
    forbidden_payloads: set[str],
    path: str = "$",
) -> list[dict[str, str]]:
    hits: list[dict[str, str]] = []
    if isinstance(value, dict):
        for key, child in value.items():
            key_text = str(key)
            key_lower = key_text.lower()
            if key_lower in forbidden_payloads or any(
                fragment in key_lower for fragment in _FORBIDDEN_KEY_FRAGMENTS
            ):
                hits.append(
                    {
                        "path": f"{path}.{key_text}",
                        "kind": "forbidden_field",
                        "match": key_text,
                    }
                )
            hits.extend(
                _forbidden_payload_hits(
                    child,
                    forbidden_payloads=forbidden_payloads,
                    path=f"{path}.{key_text}",
                )
            )
        return hits
    if isinstance(value, list):
        for index, child in enumerate(value):
            hits.extend(
                _forbidden_payload_hits(
                    child,
                    forbidden_payloads=forbidden_payloads,
                    path=f"{path}[{index}]",
                )
            )
        return hits
    if isinstance(value, str):
        lowered = value.lower()
        for forbidden in sorted(forbidden_payloads):
            if forbidden and forbidden.lower() in lowered:
                hits.append(
                    {
                        "path": path,
                        "kind": "forbidden_payload_label",
                        "match": forbidden,
                    }
                )
        for label, pattern in _SENSITIVE_VALUE_PATTERNS:
            if pattern.search(value):
                hits.append(
                    {
                        "path": path,
                        "kind": label,
                        "match": label,
                    }
                )
    return hits


def _evidence_ref_hits(evidence_refs: list[str]) -> list[dict[str, str]]:
    hits: list[dict[str, str]] = []
    for index, evidence_ref in enumerate(evidence_refs):
        if not (
            evidence_ref.startswith("docs/")
            or evidence_ref.startswith("reports/")
            or evidence_ref.startswith("owner-metadata:")
            or evidence_ref.startswith("redacted:")
        ):
            hits.append(
                {
                    "path": f"evidence_refs[{index}]",
                    "kind": "unsupported_evidence_ref_scheme",
                    "match": "unsupported_evidence_ref_scheme",
                }
            )
        for label, pattern in _SENSITIVE_VALUE_PATTERNS:
            if pattern.search(evidence_ref):
                hits.append(
                    {
                        "path": f"evidence_refs[{index}]",
                        "kind": label,
                        "match": label,
                    }
                )
    return hits


def _runtime_action_hits(forbidden_hits: list[dict[str, str]]) -> list[dict[str, str]]:
    hits: list[dict[str, str]] = []
    for hit in forbidden_hits:
        match = str(hit.get("match") or "").lower()
        path = str(hit.get("path") or "").lower()
        if any(term in match or term in path for term in _RUNTIME_ACTION_TERMS):
            hits.append(hit)
    return hits


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


def _list(value: Any) -> list[Any]:
    return value if isinstance(value, list) else []


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


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