# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-per-invocation-attenuation-when-a-delegated-aaif-warrant-s-scope-is-itself-re-scoped-by-a-downstream-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-per-invocation-attenuation-when-a-delegated-aaif-warrant-s-scope-is-itself-re-scoped-by-a-downstream-agent.warrant.json
# Markdown SHA-256:   828d8eb16c9bec00603159b2f036bf8a87585a61aeb23d0331fc70b62764e6af
# Code AST SHA-256:   3d815a1dedc5fe79579dd27a7f0b3f993b98d67c48ea487f740c403a5665aa44
# Verified Classes:   AttenuationViolation, Capability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationViolation(RuntimeError):
    """Raised when a child warrant's scope is not a sound attenuation of its parent."""


@dataclass(frozen=True)
class Capability:
    verb: str
    resource: str
    # Effective constraints = declared ∪ executor defaults, resolved before comparison.
    constraints: FrozenSet[tuple[str, str]] = field(default_factory=frozenset)

    def contains(self, other: "Capability") -> bool:
        """True iff self is at least as permissive as other (other ⊆ self)."""
        return (
            self.verb == other.verb
            and self.resource == other.resource
            # child constraints must be a SUPERSET (at least as tight) of parent's
            and self.constraints.issubset(other.constraints)
        )


def derive_child_scope(
    parent_scope: FrozenSet[Capability],
    requested_scope: FrozenSet[Capability],
) -> FrozenSet[Capability]:
    """
    The ONLY sanctioned path to a child warrant scope.
    Refuses to mint if any requested capability is not contained in some
    parent capability under lattice semantics (verb × resource × constraints).
    """
    derived: list[Capability] = []
    for req in requested_scope:
        # Find a parent capability that fully contains the request.
        covering = [p for p in parent_scope if p.contains(req)]
        if not covering:
            raise AttenuationViolation(
                f"requested capability {req.verb}:{req.resource} "
                f"constraints={sorted(req.constraints)} is not contained in any "
                f"parent capability; refusing to mint (would widen privilege)"
            )
        # Intersect constraints with the tightest covering parent to preserve bounds.
        tightest = min(covering, key=lambda p: len(p.constraints))
        derived.append(
            Capability(
                verb=req.verb,
                resource=req.resource,
                constraints=req.constraints | tightest.constraints,
            )
        )
    return frozenset(derived)


def validate_warrant_chain(
    parent_scope: FrozenSet[Capability],
    child_scope: FrozenSet[Capability],
) -> None:
    """Post-hoc validator for warrants minted outside the sanctioned path."""
    for child in child_scope:
        if not any(p.contains(child) for p in parent_scope):
            raise AttenuationViolation(
                f"child capability {child.verb}:{child.resource} "
                f"constraints={sorted(child.constraints)} escapes parent scope; "
                f"constraint substitution or resource shift detected"
            )


# --- Demonstration of the observed failure ---
if __name__ == "__main__":
    parent = frozenset({
        Capability(
            verb="read",
            resource="repo:A",
            constraints=frozenset({("paths", "/src/**"), ("max_depth", "5")}),
        )
    })
    # Planner's good-faith re-scope: dropped max_depth, added follow_symlinks.
    malicious_child = frozenset({
        Capability(
            verb="read",
            resource="repo:A",
            constraints=frozenset({("paths", "/src/**"), ("follow_symlinks", "true")}),
        )
    })
    validate_warrant_chain(parent, malicious_child)  # raises: max_depth dropped
