# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-warrant-attenuation-gap-at-a-federated-a2a-policy-enforcement-point.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-warrant-attenuation-gap-at-a-federated-a2a-policy-enforcement-point.warrant.json
# Markdown SHA-256:   a07a6d9d754e454f31fb4ff7c424f597323544e0a31f87bfd61ca7ec145d42a8
# Code AST SHA-256:   582824646a5bbb0e72e2bc4cb0d31ecfe4ba1a2fac5f455554faa1fb1251061d
# Verified Classes:   AttenuationViolation, UnintersectableChain, WarrantLink
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class AttenuationViolation(RuntimeError):
    """Raised when a delegated warrant's scope exceeds its parent's scope."""
    pass


class UnintersectableChain(RuntimeError):
    """Raised when a warrant link uses non-canonical scope encoding."""
    pass


@dataclass
class WarrantLink:
    issuer: str
    subject: str
    scope: frozenset[str]
    parent_scope_hash: str | None = None
    canonical: bool = True


def effective_scope(chain: list[WarrantLink]) -> frozenset[str]:
    if not chain:
        raise UnintersectableChain("empty warrant chain")
    result = chain[0].scope
    for i, link in enumerate(chain[1:], start=1):
        if not link.canonical:
            raise UnintersectableChain(
                f"link {i} ({link.issuer}->{link.subject}) has non-canonical scope; "
                "refusing per-link fallback"
            )
        if not link.scope.issubset(chain[i - 1].scope):
            widened = link.scope - chain[i - 1].scope
            raise AttenuationViolation(
                f"hop {i} ({link.issuer}->{link.subject}) amplifies scope by {sorted(widened)}; "
                f"parent={sorted(chain[i - 1].scope)} child={sorted(link.scope)}"
            )
        result = result & link.scope
    return result


def authorize(chain: list[WarrantLink], requested_action: str) -> dict:
    eff = effective_scope(chain)
    if requested_action not in eff:
        witness = next(
            (i for i, l in enumerate(chain) if requested_action in l.scope), None
        )
        return {
            "decision": "deny",
            "reason": "not_in_effective_scope",
            "effective_scope": sorted(eff),
            "leaf_claimed": sorted(chain[-1].scope),
            "witness_hop": witness,
        }
    return {"decision": "allow", "effective_scope": sorted(eff)}
