# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-derive-a-peer-s-capability-attestation-after-a-cross-org-federation-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-derive-a-peer-s-capability-attestation-after-a-cross-org-federation-handoff.warrant.json
# Markdown SHA-256:   5397b5788aa3fb36812959bbf70c80a549f89710744d68fe53b2d7b6c1fcfba2
# Code AST SHA-256:   98cc1430cb4b3e07a96267f98b8936701cbe9f6de558676156a26083dd1138ab
# Verified Classes:   WarrantWideningError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantWideningError(RuntimeError):
    """Raised when a re-minted warrant drops a restriction present in the origin warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    resource: str
    actions: FrozenSet[str]
    audience: FrozenSet[str]
    expiry: int
    delegate: bool
    nonce: str

    def restrictions(self) -> FrozenSet[str]:
        # Every field that constrains who/what/when is a restriction.
        r = {f"action:{a}" for a in self.actions}
        r |= {f"audience:{a}" for a in self.audience}
        r.add(f"expiry<={self.expiry}")
        r.add(f"nonce:{self.nonce}")
        if not self.delegate:
            r.add("delegate:false")
        return frozenset(r)


def forward_or_re_mint(origin: Warrant, receiver_id: str, local_alias: str) -> Warrant:
    """Cross a trust boundary. Forward byte-identical unless authorized to attenuate."""
    if not origin.delegate or receiver_id not in origin.audience:
        # Not authorized to re-mint: forward untouched, do not normalize.
        if local_alias != origin.resource:
            raise WarrantWideningError(
                f"receiver {receiver_id} cannot re-mint non-delegable warrant; "
                f"local tool layer must consume {origin.resource!r} directly"
            )
        return origin

    # Authorized to attenuate. Re-mint with local alias, preserving every restriction.
    re_minted = Warrant(
        resource=local_alias,
        actions=origin.actions,
        audience=origin.audience,
        expiry=origin.expiry,
        delegate=False,  # attenuation may only tighten
        nonce=origin.nonce,
    )

    dropped = origin.restrictions() - re_minted.restrictions()
    if dropped:
        raise WarrantWideningError(
            f"re-mint dropped restrictions {sorted(dropped)}; "
            f"refusing to emit widened warrant for {local_alias!r}"
        )
    return re_minted
