# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-verifiable-credential-trust-chains-from-silently-widening-scope-across-federated-agent-runtimes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-verifiable-credential-trust-chains-from-silently-widening-scope-across-federated-agent-runtimes.warrant.json
# Markdown SHA-256:   a79b3c2d1bc5da6be6c60c737fdcab2cff6bd684932915f54f34df99d3eb215d
# Code AST SHA-256:   e2e2e3ae927c803b677df15e554d2372a05b29feda7c2dec4d9e36eb20de82e9
# Verified Classes:   AttenuationViolation, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class AttenuationViolation(RuntimeError):
    """Raised when a delegated credential widens or fails to attenuate its parent's scope."""
    pass


@dataclass(frozen=True)
class Credential:
    issuer_did: str
    subject_did: str
    scope: frozenset[str]   # canonical, structured scope atoms -- NOT glob strings
    depth: int              # 0 == root warrant


def compute_effective_scope(
    credentials: Iterable[Credential],
    acting_did: str,
    trusted_roots: frozenset[str],
) -> frozenset[str]:
    creds = list(credentials)
    by_subject = {c.subject_did: c for c in creds}

    # 1. Locate the acting credential and reconstruct the path to a trusted root.
    if acting_did not in by_subject:
        raise AttenuationViolation(f"no credential bound to acting DID {acting_did}")

    path: list[Credential] = []
    cursor = by_subject[acting_did]
    seen: set[str] = set()
    while True:
        if cursor.subject_did in seen:
            raise AttenuationViolation(f"delegation cycle at {cursor.subject_did}")
        seen.add(cursor.subject_did)
        path.append(cursor)
        if cursor.depth == 0:
            if cursor.issuer_did not in trusted_roots:
                raise AttenuationViolation(
                    f"root issuer {cursor.issuer_did} not in trusted set"
                )
            break
        parent = by_subject.get(cursor.issuer_did)
        if parent is None:
            # 2. A derived credential whose parent is absent from the presentation
            #    cannot have its attenuation checked. Reject; do NOT fall back to
            #    the widest credential in the bag.
            raise AttenuationViolation(
                f"orphaned derived credential for {cursor.subject_did}; "
                f"parent {cursor.issuer_did} missing from presentation"
            )
        cursor = parent

    # 3. Per-hop subset enforcement, root -> leaf.
    path.reverse()
    for parent, child in zip(path, path[1:]):
        if not child.scope <= parent.scope:
            widened = child.scope - parent.scope
            raise AttenuationViolation(
                f"scope widening at hop {parent.subject_did}->{child.subject_did}: "
                f"{sorted(widened)}"
            )

    # 4. Effective authority is the path-intersection, never the union.
    effective = path[0].scope
    for c in path[1:]:
        effective = effective & c.scope
    return effective
