# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-inherit-a-broader-tool-scope-than-the-delegator-intended-the-attenuation-gap-in-agent-to-agent-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-inherit-a-broader-tool-scope-than-the-delegator-intended-the-attenuation-gap-in-agent-to-agent-delegation.warrant.json
# Markdown SHA-256:   c4d5a206bd07061d06aebc934459404c333be32fcb0d6870899a34da3bcfaf2c
# Code AST SHA-256:   69665e34e3414485ff3cc091c50b9acc46767be3b0222933fcef49d7f5855965
# Verified Classes:   AttenuationViolation, Capability, Delegation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationViolation(RuntimeError):
    """Raised when a delegated capability set is not a strict subset of the delegator's grant,
    or when a tool can escalate beyond its declared resource scope."""
    pass


@dataclass(frozen=True)
class Capability:
    tool: str
    resource_prefix: str  # enforced at call time, not in prompt text

    def covers(self, other: "Capability") -> bool:
        return self.tool == other.tool and other.resource_prefix.startswith(self.resource_prefix)


@dataclass
class Delegation:
    delegator_grant: FrozenSet[Capability]
    transmitted: FrozenSet[Capability]
    enforced: FrozenSet[Capability]  # what the runtime gateway will actually allow
    escalation_paths: FrozenSet[str] = field(default_factory=frozenset)  # tools that can reach outside their prefix


def verify_attenuation(d: Delegation) -> None:
    # 1. Transmitted must be a subset of the delegator's grant.
    for cap in d.transmitted:
        if not any(g.covers(cap) for g in d.delegator_grant):
            raise AttenuationViolation(
                f"transmitted capability {cap} exceeds delegator grant"
            )
    # 2. Enforced must equal transmitted (no silent widening at the gateway).
    if d.enforced != d.transmitted:
        widened = d.enforced - d.transmitted
        if widened:
            raise AttenuationViolation(
                f"gateway widened scope beyond declaration: {widened}"
            )
    # 3. No enforced tool may have an open escalation path.
    for cap in d.enforced:
        if cap.tool in d.escalation_paths:
            raise AttenuationViolation(
                f"tool {cap.tool} has an unclosed escalation path; "
                f"delegation would permit confused-deputy reach"
            )
    # 4. Every enforced capability must carry a resource prefix (bound handle).
    for cap in d.enforced:
        if not cap.resource_prefix:
            raise AttenuationViolation(
                f"capability {cap.tool} is unbound; resource scope is instruction-only"
            )


# Example: the observed failure, now refused before the task starts.
delegator = frozenset({
    Capability("read_file", "/data/"),
    Capability("write_file", "/data/"),
    Capability("http_post", "https://internal.example/"),
    Capability("shell", "/"),
})
# Orchestrator intended to attenuate to read-only over /data/public/.
intended = frozenset({Capability("read_file", "/data/public/")})
# But the shared template bound the full registry.
template_bound = frozenset({
    Capability("read_file", "/"),
    Capability("http_post", "https://"),
    Capability("shell", "/"),
})

verify_attenuation(Delegation(
    delegator_grant=delegator,
    transmitted=intended,
    enforced=template_bound,               # gateway allowed the template bindings
    escalation_paths=frozenset({"read_file", "shell"}),
))
# raises AttenuationViolation: gateway widened scope beyond declaration
