# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-scope-attenuation-when-a-delegated-aaif-capability-token-is-re-delegated-across-a-chain-of-autonomous-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-scope-attenuation-when-a-delegated-aaif-capability-token-is-re-delegated-across-a-chain-of-autonomous-agents.warrant.json
# Markdown SHA-256:   479af098a3fa1d159c764f6ae2370a1c6e4b6bf8f32dcba90ee41f0fda617b85
# Code AST SHA-256:   774e6069608762fdf2092050aa189aa1f05fb9d1088bf372bec84d0510202573
# Verified Classes:   AttenuationViolation, CapabilityToken
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Mapping, Optional


class AttenuationViolation(RuntimeError):
    """Raised when a child scope is not a meet (narrowing) of the parent scope."""

    def __init__(self, dimension: str, detail: str):
        super().__init__(f"attenuation violation in {dimension}: {detail}")
        self.dimension = dimension
        self.detail = detail


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    resources: FrozenSet[str]          # resource globs, e.g. {"repo:acme/*"}
    actions: FrozenSet[str]            # e.g. {"read"}
    constraints: Mapping[str, str]     # e.g. {"paths": "src/**"}
    depth: int
    max_depth: int
    exp: int                           # epoch seconds
    parent_fingerprint: Optional[str] = None

    def fingerprint(self) -> str:
        h = hashlib.sha256()
        h.update(self.subject.encode())
        h.update(b"|".join(sorted(self.resources)).encode())
        h.update(b"|".join(sorted(self.actions)).encode())
        h.update(b"|".join(f"{k}={v}" for k, v in sorted(self.constraints.items())).encode())
        h.update(f"{self.depth}:{self.max_depth}:{self.exp}".encode())
        return h.hexdigest()


def _subset_resources(child: FrozenSet[str], parent: FrozenSet[str]) -> bool:
    # A resource glob is a subset only if every child glob is covered by some parent glob.
    # Prefix coverage is conservative; a production impl would use a glob-lattice library.
    for c in child:
        if not any(c == p or c.startswith(p.rstrip("*")) for p in parent):
            return False
    return True


def mint_child(
    parent: CapabilityToken,
    subject: str,
    requested_resources: FrozenSet[str],
    requested_actions: FrozenSet[str],
    requested_constraints: Mapping[str, str],
    requested_exp: int,
) -> CapabilityToken:
    """Mint an attenuated child token, or fail closed on any widening."""

    # 1. Depth lattice: child is parent.depth + 1, bounded by parent.max_depth.
    child_depth = parent.depth + 1
    if child_depth > parent.max_depth:
        raise AttenuationViolation(
            "depth", f"child depth {child_depth} exceeds max_depth {parent.max_depth}"
        )

    # 2. Resource lattice: child resources must be covered by parent resources.
    if not _subset_resources(requested_resources, parent.resources):
        raise AttenuationViolation(
            "resources",
            f"requested {sorted(requested_resources)} not covered by {sorted(parent.resources)}",
        )

    # 3. Action lattice: meet is intersection. Any requested action outside parent is a widening.
    widened_actions = requested_actions - parent.actions
    if widened_actions:
        raise AttenuationViolation(
            "actions", f"requested actions {sorted(widened_actions)} not granted by parent"
        )
    child_actions = requested_actions & parent.actions

    # 4. Constraint lattice: parent constraints are inherited; child may only add/narrow.
    child_constraints = dict(parent.constraints)
    for k, v in requested_constraints.items():
        if k in parent.constraints and v != parent.constraints[k]:
            # Narrowing a constraint requires a lattice-specific check; be conservative.
            raise AttenuationViolation(
                "constraints",
                f"constraint {k!r} changed from {parent.constraints[k]!r} to {v!r} "
                "without a verified narrowing relation",
            )
        child_constraints[k] = v

    # 5. Expiry lattice: child may not outlive parent.
    if requested_exp > parent.exp:
        raise AttenuationViolation(
            "expiry", f"child exp {requested_exp} exceeds parent exp {parent.exp}"
        )

    return CapabilityToken(
        subject=subject,
        resources=requested_resources,
        actions=child_actions,
        constraints=child_constraints,
        depth=child_depth,
        max_depth=parent.max_depth,
        exp=requested_exp,
        parent_fingerprint=parent.fingerprint(),
    )


def verify_chain(tokens: list) -> CapabilityToken:
    """Recompute the meet from root to leaf; never trust a child's serialized scope."""
    if not tokens:
        raise AttenuationViolation("chain", "empty delegation chain")
    root = tokens[0]
    current = root
    for child in tokens[1:]:
        if child.parent_fingerprint != current.fingerprint():
            raise AttenuationViolation(
                "chain", f"parent fingerprint mismatch at depth {child.depth}"
            )
        # Re-mint from the parent to confirm the child is an exact meet.
        recomputed = mint_child(
            current,
            child.subject,
            child.resources,
            child.actions,
            child.constraints,
            child.exp,
        )
        if recomputed.fingerprint() != child.fingerprint():
            raise AttenuationViolation(
                "chain",
                f"child at depth {child.depth} is not a meet of its parent",
            )
        current = child
    return current
