# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegation-chain-in-aaif-verifiable-credential-issuance-for-autonomous-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegation-chain-in-aaif-verifiable-credential-issuance-for-autonomous-agents.warrant.json
# Markdown SHA-256:   8681b54e9e8d11f3dcb553f5ddea07275b20f6f613a4803e7f8f13f33a569e47
# Code AST SHA-256:   b92016b0f8d3a3f94b5f97dfab073768abb1afece4710005831e8e6cab83277d
# Verified Classes:   AttenuationViolation, Scope, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationViolation(RuntimeError):
    """Raised when a child credential's effective scope is not a subset of its parent's."""
    pass


@dataclass(frozen=True)
class Scope:
    actions: FrozenSet[str]
    resources: FrozenSet[str]  # already canonicalized by the enforcement matcher

    def is_subset_of(self, parent: "Scope") -> bool:
        return self.actions <= parent.actions and self.resources <= parent.resources

    def widening_delta(self, parent: "Scope") -> dict:
        return {
            "extra_actions": sorted(self.actions - parent.actions),
            "extra_resources": sorted(self.resources - parent.resources),
        }


@dataclass
class Credential:
    subject: str
    scope: Scope
    parent_hash: str | None
    delegation_depth: int
    history: list = field(default_factory=list)


def issue_delegation(
    parent: Credential,
    child_subject: str,
    requested_scope: Scope,
    max_depth: int = 4,
) -> Credential:
    if parent.delegation_depth + 1 > max_depth:
        raise AttenuationViolation(
            f"delegation depth {parent.delegation_depth + 1} exceeds max {max_depth}"
        )

    # The invariant: child effective scope MUST be a subset of parent effective scope.
    # This is checked structurally, against the enforcement canonicalizer, never by prompt.
    if not requested_scope.is_subset_of(parent.scope):
        delta = requested_scope.widening_delta(parent.scope)
        raise AttenuationViolation(
            f"child scope for {child_subject!r} widens parent {parent.subject!r}: {delta}"
        )

    return Credential(
        subject=child_subject,
        scope=requested_scope,
        parent_hash=hash((parent.subject, parent.scope, parent.parent_hash)),
        delegation_depth=parent.delegation_depth + 1,
        history=parent.history + [parent.subject],
    )


def verify_chain(leaf: Credential, root: Credential) -> bool:
    # Recompute effective scope by walking to root; never trust intermediate declarations.
    if leaf.delegation_depth == 0:
        return leaf.scope.is_subset_of(root.scope)
    if not leaf.scope.is_subset_of(root.scope):
        raise AttenuationViolation(
            f"leaf {leaf.subject!r} exceeds root {root.subject!r} after chain walk"
        )
    return True


# Example trigger: LLM compiler widened actions and over-captured a glob.
root = Credential(
    subject="orchestrator",
    scope=Scope(actions=frozenset({"read", "list"}),
                resources=frozenset({"repo:acme/widgets/*"})),
    parent_hash=None,
    delegation_depth=0,
)

bad_child_scope = Scope(
    actions=frozenset({"read", "list", "write"}),          # widened
    resources=frozenset({"repo:acme/widgets/frontend/**"}),  # disjoint after canonicalization
)

issue_delegation(root, "reviewer", bad_child_scope)  # raises AttenuationViolation
