# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-when-trust-broker-attestation-chains-exhibit-non-monotonic-policy-attenuation-a.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-when-trust-broker-attestation-chains-exhibit-non-monotonic-policy-attenuation-a.warrant.json
# Markdown SHA-256:   8d70bf608c575dd14ec513909a6b70cd6b168f7fc0d7faf1e7f5f03b97cb1531
# Code AST SHA-256:   3408a29a3ba46a8693320c92b1e36594b924d23feb85dfc13f5605e66a09a343
# Verified Classes:   AttenuationViolation, Hop, Chain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import FrozenSet, Sequence


class AttenuationViolation(RuntimeError):
    """Raised when a federated attestation chain is integrity-valid but
    fails the monotonic-attenuation invariant: eff(terminal) must be a
    subset of eff(origin), and every broker hop must be non-widening."""


@dataclass(frozen=True)
class Hop:
    broker_id: str
    # Dimensions the source policy carried that this dialect cannot express.
    dropped_dimensions: FrozenSet[str] = frozenset()
    # Effective capability set as reconstructed at this hop.
    effective: FrozenSet[str] = frozenset()
    # Broker's own claim that eff(target) <= eff(source); None if absent.
    non_widening_asserted: bool | None = None


@dataclass(frozen=True)
class Chain:
    origin_effective: FrozenSet[str]
    hops: Sequence[Hop]
    local_policy: FrozenSet[str] = field(default_factory=frozenset)


def admit(chain: Chain) -> FrozenSet[str]:
    """Return the admitted effective capability set, or raise."""
    prev = chain.origin_effective

    for hop in chain.hops:
        # 1. A dropped dimension is an unrecoverable widening.
        if hop.dropped_dimensions:
            raise AttenuationViolation(
                f"broker {hop.broker_id} dropped dimensions "
                f"{sorted(hop.dropped_dimensions)}; qualifier not machine-enforceable"
            )
        # 2. Per-hop subset check, independent of signature validity.
        if not hop.effective <= prev:
            widened = sorted(hop.effective - prev)
            raise AttenuationViolation(
                f"broker {hop.broker_id} widened scope by {widened}"
            )
        # 3. Absent non-widening assertion means the hop is a widening risk.
        if hop.non_widening_asserted is not True:
            raise AttenuationViolation(
                f"broker {hop.broker_id} produced no verifiable non-widening assertion"
            )
        prev = hop.effective

    terminal = prev
    # 4. Terminal must still be a subset of origin (redundant if hops are
    #    correct, but cheap and catches reconstruction bugs).
    if not terminal <= chain.origin_effective:
        raise AttenuationViolation("terminal scope exceeds origin scope")
    # 5. Local policy is the floor.
    if not terminal <= chain.local_policy:
        raise AttenuationViolation(
            f"terminal scope exceeds local policy: {sorted(terminal - chain.local_policy)}"
        )
    return terminal


def _demo() -> None:
    # Reproduces the C-17 trace: B1 drops 'purpose', B2 widens to write/export.
    origin = frozenset({"telemetry:read"})
    b1 = Hop("B1", dropped_dimensions=frozenset({"purpose"}), effective=origin,
             non_widening_asserted=True)
    b2 = Hop("B2", effective=frozenset({"telemetry:read", "telemetry:write",
                                        "telemetry:export"}),
             non_widening_asserted=True)
    try:
        admit(Chain(origin_effective=origin, hops=[b1, b2],
                    local_policy=frozenset({"telemetry:read"})))
    except AttenuationViolation as exc:
        print(f"REJECTED: {exc}")


if __name__ == "__main__":
    _demo()
