# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-a-foreign-trust-anchor-when-policy-translation-collapses-two-distinct-scopes-into-one.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-a-foreign-trust-anchor-when-policy-translation-collapses-two-distinct-scopes-into-one.warrant.json
# Markdown SHA-256:   3669d993bb288daf81b170b0896e60592059512fb573fe93a2169c18e6bb7b87
# Code AST SHA-256:   49549027c1b96926ca7d1234bfb31f636396edc1713642db4b67867317e7fb2d
# Verified Classes:   ScopeCollapseError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ScopeCollapseError(RuntimeError):
    """Raised when a foreign warrant's delegation and execution scopes cannot be
    safely reconciled into a local capability set."""


SCOPE_BEARING_TOKENS = ("scope", "cap", "grant", "tier", "degraded", "override")


def translate_foreign_warrant(
    signed_payload: dict,
    known_fields: set[str],
    local_scope_map: dict[str, str],
) -> frozenset[str]:
    # 1. Closed-schema check: any unknown scope-bearing field halts translation.
    unknown = set(signed_payload) - known_fields
    for field in unknown:
        lowered = field.lower()
        if any(tok in lowered for tok in SCOPE_BEARING_TOKENS):
            raise ScopeCollapseError(
                f"unknown scope-bearing field {field!r} in signed payload; "
                "translation must halt rather than discard"
            )

    # 2. Both scopes must be present and signed.
    try:
        delegated = set(signed_payload["delegated_scope"])
        effective = set(signed_payload["effective_scope"])
    except KeyError as exc:
        raise ScopeCollapseError(
            f"warrant missing required signed scope field: {exc.args[0]!r}"
        ) from exc

    # 3. Issuer-declared degradation forbids translation entirely; the receiver
    #    must re-derive against the issuer's live policy state before proceeding.
    if signed_payload.get("degraded") is True:
        raise ScopeCollapseError(
            "issuer warrant is marked degraded; effective_scope is not "
            "authoritative and translation must be re-derived against the "
            "issuer's signed degradation-status endpoint"
        )

    # 4. Invariant: translated set is the intersection, never the union.
    authoritative = delegated & effective
    if not authoritative:
        raise ScopeCollapseError(
            "delegation and execution scopes do not intersect; no permission "
            "can be safely translated"
        )

    # 5. Map through the local scope table; unknown foreign scopes fail closed.
    try:
        return frozenset(local_scope_map[s] for s in authoritative)
    except KeyError as exc:
        raise ScopeCollapseError(
            f"foreign scope {exc.args[0]!r} has no local translation; "
            "refusing to widen"
        ) from exc
