# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-federation-policy-engine-has-silently-widened-capability-attenuation-at-the-residency-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-federation-policy-engine-has-silently-widened-capability-attenuation-at-the-residency-boundary.warrant.json
# Markdown SHA-256:   eedc1f620a3418fab991278f829f4d217fd8446d81def715c25ec6be3160d5b9
# Code AST SHA-256:   b5f123f30ded76ea3ee39fc03380624029313c06c62d863dbc1a9f099eadee05
# Verified Classes:   CapabilityWideningError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityWideningError(RuntimeError):
    """Raised when a return warrant is not a monotone attenuation of the stored outbound grant."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    actions: FrozenSet[str]
    residency: str  # e.g. "EU-only", "global"
    ttl_s: int


# Residency refinement lattice: a child label must be equal-or-stricter than parent.
_RESIDENCY_RANK = {"global": 0, "EU-only": 1, "EU-only:no-export": 2}


def _is_refinement(child: str, parent: str) -> bool:
    return _RESIDENCY_RANK.get(child, -1) >= _RESIDENCY_RANK.get(parent, -1)


def issue_return_warrant(
    outbound: Warrant,
    payload_provenance_actions: FrozenSet[str],
    payload_residency: str,
) -> Warrant:
    """
    Re-derive the inbound warrant. The payload may only NARROW the stored grant.
    Any declared action or residency outside the stored outbound grant is an
    over-declaration and must be discarded, never propagated.
    """
    widened_actions = payload_provenance_actions - outbound.actions
    if widened_actions:
        # Over-declaration: agent claimed actions it was never granted.
        # Do NOT propagate; log and intersect against the authoritative grant.
        pass

    # Correct attenuation: intersect against the STORED grant, not the payload.
    child_actions = payload_provenance_actions & outbound.actions

    if not _is_refinement(payload_residency, outbound.residency):
        raise CapabilityWideningError(
            f"return warrant residency {payload_residency!r} relaxes stored "
            f"grant {outbound.residency!r} for warrant {outbound.warrant_id}"
        )

    # Monotonicity invariant: child must be a subset of the authoritative parent.
    if not child_actions.issubset(outbound.actions):
        raise CapabilityWideningError(
            f"return warrant actions {sorted(child_actions)} not subset of "
            f"stored grant {sorted(outbound.actions)} for {outbound.warrant_id}"
        )

    return Warrant(
        warrant_id=outbound.warrant_id,  # bound to the same id
        actions=frozenset(child_actions),
        residency=payload_residency,
        ttl_s=min(outbound.ttl_s, 300),
    )


def assert_monotone_round_trip(outbound: Warrant, inbound: Warrant) -> None:
    if inbound.warrant_id != outbound.warrant_id:
        raise CapabilityWideningError(
            f"return warrant id {inbound.warrant_id!r} not bound to outbound "
            f"{outbound.warrant_id!r}; cannot verify monotonicity"
        )
    if not inbound.actions.issubset(outbound.actions):
        raise CapabilityWideningError(
            f"lattice violation: inbound actions {sorted(inbound.actions)} "
            f"exceed outbound {sorted(outbound.actions)}"
        )
