# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-attenuation-from-silently-re-escalating-across-federated-task-spaces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-attenuation-from-silently-re-escalating-across-federated-task-spaces.warrant.json
# Markdown SHA-256:   58919305d6e954d3555332ec4baa58aaa61beadbdf02715fcfe6adafef3587f2
# Code AST SHA-256:   30f998bbeeecd0996b77dbb00acceeaffca1b7d8ba5c571b0c2e89ef34571209
# Verified Classes:   AttenuationEscape, Capability, Policy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationEscape(RuntimeError):
    """Raised when a delegated capability would resolve to broader authority
    than the delegator's policy permits, at the point of use."""


@dataclass(frozen=True)
class Capability:
    tool: str
    hosts: FrozenSet[str]
    ttl_s: int
    artifact_reads: FrozenSet[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class Policy:
    allowed_hosts: FrozenSet[str]
    allowed_tools: FrozenSet[str]
    artifact_reads: FrozenSet[str]
    # Resolution model matters: "intersect" is sound; "precedence" is not.
    resolution: str = "intersect"


def resolve_effective(
    cap: Capability,
    delegator_policy: Policy,
    task_space_policy: Policy,
) -> Capability:
    """Compute the effective capability at the point of use.

    Sound only if both policies are joined by intersection. If either policy
    resolves by precedence (ambient grants override delegated), the effective
    capability can exceed the delegator's authority and we must refuse.
    """
    for name, pol in (("delegator", delegator_policy), ("task_space", task_space_policy)):
        if pol.resolution != "intersect":
            raise AttenuationEscape(
                f"{name} policy uses resolution={pol.resolution!r}; "
                "precedence-based resolution can silently widen delegated authority"
            )

    if cap.tool not in delegator_policy.allowed_tools:
        raise AttenuationEscape(
            f"tool {cap.tool!r} not permitted by delegator policy"
        )

    effective_hosts = cap.hosts & delegator_policy.allowed_hosts & task_space_policy.allowed_hosts
    if not effective_hosts:
        raise AttenuationEscape(
            f"capability {cap.tool!r} has no host surviving intersection "
            f"(cap={sorted(cap.hosts)}, delegator={sorted(delegator_policy.allowed_hosts)}, "
            f"space={sorted(task_space_policy.allowed_hosts)})"
        )

    effective_artifacts = (
        cap.artifact_reads
        & delegator_policy.artifact_reads
        & task_space_policy.artifact_reads
    )
    # Artifact reads are NOT inherited from space membership; absence of an
    # explicit grant in the capability means no read, even if the space default
    # would have granted it.
    if not cap.artifact_reads and task_space_policy.artifact_reads:
        effective_artifacts = frozenset()

    return Capability(
        tool=cap.tool,
        hosts=effective_hosts,
        ttl_s=cap.ttl_s,
        artifact_reads=effective_artifacts,
    )


def admit_call(effective: Capability, tool: str, host: str) -> None:
    if tool != effective.tool:
        raise AttenuationEscape(f"tool mismatch: {tool!r} != {effective.tool!r}")
    if host not in effective.hosts:
        raise AttenuationEscape(
            f"host {host!r} outside effective scope {sorted(effective.hosts)}"
        )
