# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-policy-version-authority-at-the-trust-broker-handoff-boundary-during-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-policy-version-authority-at-the-trust-broker-handoff-boundary-during-cross-org-federation.warrant.json
# Markdown SHA-256:   0f6032114052e8021f7b13591235e61f2308915aaae741466ede925f79916812
# Code AST SHA-256:   26c8e0b43a6eababbbe05d5bcad02d11f2c19128aa03d2047d19246908c99f7a
# Verified Classes:   PolicyEpochMismatch, PolicyCache
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PolicyEpochMismatch(RuntimeError):
    """Raised when a warrant's policy_ref cannot be resolved to an exact
    epoch match in the receiver's cache. Fail-closed: never fall back to
    nearest-match, last-known-good, or default policy."""
    pass


class PolicyCache:
    def __init__(self, store: dict[str, dict]):
        # store maps exact epoch -> policy document
        self._store = store

    def resolve_exact(self, policy_ref: str) -> dict:
        if policy_ref not in self._store:
            raise PolicyEpochMismatch(
                f"policy epoch {policy_ref!r} not present in local cache; "
                f"available={sorted(self._store)}; refusing fallback"
            )
        return self._store[policy_ref]


def enforce_warrant(warrant: dict, cache: PolicyCache) -> dict:
    policy_ref = warrant["policy_ref"]
    try:
        policy = cache.resolve_exact(policy_ref)
    except PolicyEpochMismatch as e:
        # Terminal condition of the warrant — do not execute, do not retry
        # under a different epoch. Emit a receipt so the broker can reconcile.
        return {
            "warrant_id": warrant["warrant_id"],
            "minted_epoch": policy_ref,
            "enforced_epoch": None,
            "decision": "aborted_epoch_mismatch",
            "detail": str(e),
        }

    subject_tier = warrant["subject"]["tier"]
    rule = policy["rules"].get(warrant["scope"])
    if rule is None:
        return {
            "warrant_id": warrant["warrant_id"],
            "minted_epoch": policy_ref,
            "enforced_epoch": policy_ref,
            "decision": "denied_no_rule",
        }
    if rule.get("require_tier") and subject_tier != rule["require_tier"]:
        return {
            "warrant_id": warrant["warrant_id"],
            "minted_epoch": policy_ref,
            "enforced_epoch": policy_ref,
            "decision": "denied_tier",
        }
    return {
        "warrant_id": warrant["warrant_id"],
        "minted_epoch": policy_ref,
        "enforced_epoch": policy_ref,
        "decision": "allowed",
    }


def reconcile_receipts(receipts: list[dict]) -> None:
    """Cross-component epoch join. Any row where minted != enforced is a
    federation seam event and must be surfaced, not swallowed."""
    for r in receipts:
        if r["enforced_epoch"] is not None and r["minted_epoch"] != r["enforced_epoch"]:
            raise PolicyEpochMismatch(
                f"seam event: warrant {r['warrant_id']} minted under "
                f"{r['minted_epoch']} but enforced under {r['enforced_epoch']}"
            )
