# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-trust-broker-policy-translation-drift-that-silently-widens-its-effective-capability-envelope-during-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-trust-broker-policy-translation-drift-that-silently-widens-its-effective-capability-envelope-during-cross-org-federation.warrant.json
# Markdown SHA-256:   c407fb07a2faa87a99c114663512967eb773cc0fbf004c283749662bbe94b213
# Code AST SHA-256:   0c21b2c542d670b1ae0281583d1dbf421f5305731fd4474550c43f500e4005ff
# Verified Classes:   TranslationDriftError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet

class TranslationDriftError(RuntimeError):
    """Raised when a broker-translated scope is not provably a subset of the attested origin scope."""
    pass

@dataclass(frozen=True)
class Warrant:
    capability: str
    scope: FrozenSet[str]
    dialect: str
    origin: "Warrant | None" = None
    translation_proof: str | None = None  # broker-signed subset attestation, if any

def _reparse_to_origin(scope: FrozenSet[str], dst_dialect: str, origin_dialect: str) -> FrozenSet[str] | None:
    # Inverse translation T^-1; returns None if the dialect pair cannot express the inverse exactly.
    if dst_dialect == origin_dialect:
        return scope
    # A glob in the destination dialect cannot be inverted to a finite origin set.
    if any("*" in s for s in scope):
        return None
    return scope

def admit_warrant(w: Warrant, origin_manifest: FrozenSet[str]) -> FrozenSet[str]:
    """Return the executable scope, or raise if the subset invariant cannot be established."""
    if w.origin is None:
        # Direct warrant, no translation hop.
        return w.scope

    if w.translation_proof is None:
        # Untrusted-translation regime: intersect against the origin manifest, fail closed on gaps.
        executable = w.scope & origin_manifest
        if executable != w.scope:
            raise TranslationDriftError(
                f"translated scope {sorted(w.scope)} exceeds origin manifest "
                f"{sorted(origin_manifest)}; refusing to execute widened scope"
            )
        return executable

    # Trusted-translation regime: verify the broker's subset proof by round-trip.
    inverted = _reparse_to_origin(w.scope, w.dialect, w.origin.dialect)
    if inverted is None:
        raise TranslationDriftError(
            f"dialect pair ({w.origin.dialect}->{w.dialect}) has no exact inverse; "
            f"translation_proof is unverifiable, refusing"
        )
    if not inverted.issubset(w.origin.scope):
        raise TranslationDriftError(
            f"broker proof claims subset but round-trip {sorted(inverted)} "
            f"is not within attested {sorted(w.origin.scope)}"
        )
    return w.scope
