# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-authority-attenuation-has-silently-collapsed-in-agent-to-agent-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-authority-attenuation-has-silently-collapsed-in-agent-to-agent-delegation-chains.warrant.json
# Markdown SHA-256:   fa422eceffea68c4bd131da01e149ddb27beeee85ab6124945a34f43e19536f2
# Code AST SHA-256:   bb2b8cf11cbdfdebfb0fbdee76d5f68252a2a71c4328f0e786ee8ddcbcf1a7d6
# Verified Classes:   AttenuationCollapse, Warrant, ChainAuditor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationCollapse(RuntimeError):
    """Raised when a delegated warrant's effective authority exceeds its bound."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str                 # agent this warrant was issued to
    chain_id: str                # delegation chain this warrant belongs to
    issuer: str                  # agent that issued it (None-equivalent for root)
    scopes: FrozenSet[str]       # declared scope labels
    tools: FrozenSet[str]        # declared tool grants
    signature_valid: bool = True
    expired: bool = False


@dataclass
class ChainAuditor:
    # scope label -> set of effect-classes the tool boundary actually permits
    referent_map: dict = field(default_factory=dict)
    # tool name -> effect-classes it can reach
    tool_effects: dict = field(default_factory=dict)

    def effective_effects(self, w: Warrant) -> FrozenSet[str]:
        effects = set()
        for scope in w.scopes:
            # A scope with no declared referent closure is UNBOUNDED.
            effects |= self.referent_map.get(scope, {"*"})
        for tool in w.tools:
            effects |= self.tool_effects.get(tool, {"*"})
        return frozenset(effects)

    def validate_hop(self, parent: Warrant, child: Warrant,
                     presenting_agent: str) -> None:
        # (2) issuer binding: subject and chain identity must match presentation
        if child.subject != presenting_agent:
            raise AttenuationCollapse(
                f"warrant subject {child.subject!r} presented by "
                f"{presenting_agent!r}: replay across agents"
            )
        if child.chain_id != parent.chain_id:
            raise AttenuationCollapse(
                f"chain_id mismatch: {child.chain_id!r} vs {parent.chain_id!r}"
            )
        if not child.signature_valid or child.expired:
            raise AttenuationCollapse("warrant failed signature/expiry check")

        # (3) depth monotonicity: effective effects must be a subset of parent's
        parent_eff = self.effective_effects(parent)
        child_eff = self.effective_effects(child)
        escaped = child_eff - parent_eff
        if escaped:
            raise AttenuationCollapse(
                f"effective authority escape at hop {parent.subject}->{child.subject}: "
                f"{sorted(escaped)} not bounded by parent"
            )

    def validate_chain(self, hops: list, presenters: list) -> None:
        for i in range(1, len(hops)):
            self.validate_hop(hops[i - 1], hops[i], presenters[i])


def demo_collapse() -> None:
    auditor = ChainAuditor(
        # fs:read has NO referent closure -> unbounded by design flaw
        referent_map={"fs:read": {"*"}, "fs:write": {"*"}, "net:egress": {"*"},
                      "shell:exec": {"*"}},
        tool_effects={"read_file": {"*"}, "write_file": {"*"}},
    )
    root = Warrant("O", "chain-1", None,
                   frozenset({"fs:read", "fs:write", "net:egress", "shell:exec"}),
                   frozenset({"read_file", "write_file"}))
    planner = Warrant("P", "chain-1", "O",
                      frozenset({"fs:read", "net:egress"}),
                      frozenset({"read_file"}))
    executor = Warrant("E", "chain-1", "P",
                       frozenset({"fs:read"}),
                       frozenset({"read_file"}))

    # Declared sets shrink monotonically; the audit narrative looks correct.
    assert executor.scopes < planner.scopes < root.scopes

    # But effective effects do not shrink: fs:read resolves to '*'.
    auditor.validate_chain([root, planner, executor], ["O", "P", "E"])
    # ^ raises AttenuationCollapse because parent_eff == child_eff == {'*'} is
    #   a subset, so this specific check passes -> collapse is invisible here.


if __name__ == "__main__":
    demo_collapse()
