# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cross-organizational-task-commitment-as-revocable-despite-a-quorum-of-signatures.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cross-organizational-task-commitment-as-revocable-despite-a-quorum-of-signatures.warrant.json
# Markdown SHA-256:   abb3f703c4b658222d8aac69183fa775ff0f67bfc340e2a1c2fe69c72cda2870
# Code AST SHA-256:   2b3d112f8d2c0ddaef3506f59a24df4236da4b8e0ece69377d0af9088cfc0ca6
# Verified Classes:   CrossOrgCommitmentError, RegistryPin, CommitmentCertificate, VerifierView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping, Optional


class CrossOrgCommitmentError(RuntimeError):
    """Raised when a cross-organizational commitment cannot be treated as irrevocable."""


@dataclass(frozen=True)
class RegistryPin:
    org_id: str
    version: int
    merkle_root: str


@dataclass
class CommitmentCertificate:
    task_digest: str
    signatures: Mapping[str, bytes]          # signer_id -> signature
    registry_pins: Mapping[str, RegistryPin] # org_id -> pinned registry view
    propagation_barrier_closed: bool


@dataclass
class VerifierView:
    # Authoritative local view of each org's registry, as of evaluation time.
    registry_versions: Mapping[str, int]
    registry_roots: Mapping[str, str]
    revocation_list: Mapping[str, set]       # org_id -> revoked key ids
    equivocation_evidence_portable: bool


def evaluate_commitment(
    cert: CommitmentCertificate,
    view: VerifierView,
    quorum_threshold: int,
    signer_org: Mapping[str, str],           # signer_id -> org_id
) -> str:
    """
    Returns 'irrevocable' or 'provisional'.
    Raises CrossOrgCommitmentError when the certificate is structurally
    incapable of finality across an organizational boundary.
    """
    if len(cert.signatures) < quorum_threshold:
        raise CrossOrgCommitmentError(
            f"insufficient signatures: {len(cert.signatures)} < {quorum_threshold}"
        )

    # Invariant 1: every signer org must be pinned.
    signer_orgs = {signer_org[s] for s in cert.signatures}
    missing_pins = signer_orgs - set(cert.registry_pins)
    if missing_pins:
        raise CrossOrgCommitmentError(
            f"certificate lacks registry pins for orgs: {sorted(missing_pins)}"
        )

    # Invariant 2: pins must match the verifier's authoritative view exactly.
    # "Newer" is as dangerous as "older": a newer registry may have re-revoked
    # a key that the certificate counted toward quorum.
    for org_id in signer_orgs:
        pin = cert.registry_pins[org_id]
        local_version = view.registry_versions.get(org_id)
        local_root = view.registry_roots.get(org_id)
        if local_version is None or local_root is None:
            raise CrossOrgCommitmentError(
                f"no authoritative registry view for org {org_id!r}"
            )
        if pin.version != local_version or pin.merkle_root != local_root:
            raise CrossOrgCommitmentError(
                f"registry pin mismatch for org {org_id!r}: "
                f"pinned v{pin.version}/{pin.merkle_root[:8]}, "
                f"local v{local_version}/{local_root[:8]}"
            )

    # Invariant 3: revocation must be evaluated against the pinned snapshot,
    # not the verifier's own local revocation list applied to foreign signers.
    for signer_id in cert.signatures:
        org_id = signer_org[signer_id]
        if signer_id in view.revocation_list.get(org_id, set()):
            # This is a hard failure: the certificate counted a revoked signer
            # toward quorum. It must not be silently downgraded to provisional,
            # because the quorum itself is invalid.
            raise CrossOrgCommitmentError(
                f"signer {signer_id!r} is revoked in org {org_id!r} at pinned version"
            )

    # Invariant 4: equivocation evidence must be portable across the boundary.
    if not view.equivocation_evidence_portable:
        return "provisional"

    # Invariant 5: the propagation barrier must be closed before irrevocable
    # execution. An open barrier means a signer may have signed with a key
    # the verifier cannot yet see.
    if not cert.propagation_barrier_closed:
        return "provisional"

    return "irrevocable"
