# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-credential-whose-scope-was-widened-by-an-intermediate-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-credential-whose-scope-was-widened-by-an-intermediate-agent.warrant.json
# Markdown SHA-256:   3f1948956a53b20719bf94f7b72cbd654ef24f6cfdc680d601b21729330f5c2f
# Code AST SHA-256:   fe0bf86ec17473bb001652207d505d4e5849b50da7c93917b19f01fa9f43bf7a
# Verified Classes:   ScopeConservationError, CapabilityAtom, Credential, DeltaAttestation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeConservationError(RuntimeError):
    """Raised when a delegated credential's scope exceeds its parent's attested scope
    without a valid delta attestation from an authorized principal."""


@dataclass(frozen=True)
class CapabilityAtom:
    action: str          # e.g. "write"
    resource: str        # e.g. "branch/feature-x"  (canonical form, post-parse)
    constraints: FrozenSet[str]  # e.g. frozenset({"branch=feature-x"})

    def is_subset_of(self, other: "CapabilityAtom") -> bool:
        # same action+resource, and every constraint here is also in other
        # (dropping a constraint widens; adding one narrows)
        return (
            self.action == other.action
            and self.resource == other.resource
            and self.constraints.issubset(other.constraints)
        )


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject: str
    scope: FrozenSet[CapabilityAtom]
    parent_scope: FrozenSet[CapabilityAtom] | None   # attested scope of issuer's own inbound cred
    delta_attestation: "DeltaAttestation | None"
    signature_valid: bool


@dataclass(frozen=True)
class DeltaAttestation:
    attesting_principal: str
    covered_atoms: FrozenSet[CapabilityAtom]
    bound_nonce: str
    signature_valid: bool


def verify_delegation(
    cred: Credential,
    trusted_issuers: FrozenSet[str],
    trusted_attesters: FrozenSet[str],
    expected_nonce: str,
) -> None:
    if not cred.signature_valid:
        raise ScopeConservationError(f"bad signature on credential from {cred.issuer}")
    if cred.issuer not in trusted_issuers:
        raise ScopeConservationError(f"untrusted issuer {cred.issuer}")

    # Cold-start / resume: parent scope unavailable => cannot prove conservation.
    if cred.parent_scope is None:
        raise ScopeConservationError(
            f"parent attested scope missing for {cred.subject}; "
            "treat as unattested and refuse privileged atoms"
        )

    delta = cred.scope - cred.parent_scope
    if not delta:
        return  # conservation holds

    # Widening occurred. Require a fresh attestation covering every widened atom.
    att = cred.delta_attestation
    if att is None:
        raise ScopeConservationError(
            f"scope laundering: {cred.issuer} widened {sorted(a.resource for a in delta)} "
            "with no delta attestation"
        )
    if not att.signature_valid or att.attesting_principal not in trusted_attesters:
        raise ScopeConservationError("delta attestation not from a trusted principal")
    if att.bound_nonce != expected_nonce:
        raise ScopeConservationError("delta attestation nonce mismatch (replay or stale)")
    uncovered = {a for a in delta if not any(a.is_subset_of(c) for c in att.covered_atoms)}
    if uncovered:
        raise ScopeConservationError(
            f"delta attestation does not cover widened atoms: "
            f"{sorted(a.resource for a in uncovered)}"
        )
    # conservation satisfied via legitimate re-delegation; caller may proceed and log
