# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-chain-verifies-but-whose-attenuation-scope-was-computed-against-a-supe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-chain-verifies-but-whose-attenuation-scope-was-computed-against-a-supe.warrant.json
# Markdown SHA-256:   ed6528e64c835642f440822d4aed175f4fb3f5a1239d938ddff8c44505133acd
# Code AST SHA-256:   9c010334c4f0eb084bdb455357ccb6c66202465c0c00027ced0fb87347140ff5
# Verified Classes:   ManifestSkewError, UndefinedScopeError, AttenuationViolationError, Link
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class ManifestSkewError(RuntimeError):
    """Raised when adjacent delegation links were signed over different capability manifests."""


class UndefinedScopeError(RuntimeError):
    """Raised when a delegated scope token is not defined in the manifest version it is checked against."""


class AttenuationViolationError(RuntimeError):
    """Raised when a child scope resolves to a strictly wider capability set than its parent."""


@dataclass(frozen=True)
class Link:
    subject: str
    scope_tokens: frozenset[str]
    manifest_version: str


# manifest_version -> token -> concrete capability set (paths, hosts, etc.)
MANIFESTS: Mapping[str, Mapping[str, frozenset[str]]] = {
    "v7": {
        "tool:filesystem:write": frozenset({"/data"}),
        "net:egress:internal": frozenset({"10.0.0.0/8"}),
    },
    "v8": {
        "tool:filesystem:write": frozenset({"/data/staging"}),
        "net:egress:corp": frozenset({"10.0.0.0/8"}),
    },
}


def _resolve(scope_tokens: frozenset[str], manifest_version: str) -> frozenset[str]:
    manifest = MANIFESTS[manifest_version]
    resolved: set[str] = set()
    for token in scope_tokens:
        if token not in manifest:
            raise UndefinedScopeError(
                f"token {token!r} undefined in manifest {manifest_version!r}"
            )
        resolved |= manifest[token]
    return frozenset(resolved)


def verify_chain(links: list[Link]) -> None:
    """Verify provenance AND attenuation soundness across a delegation chain."""
    if not links:
        return
    for parent, child in zip(links, links[1:]):
        if parent.manifest_version != child.manifest_version:
            raise ManifestSkewError(
                f"{parent.subject}->{child.subject}: manifest skew "
                f"{parent.manifest_version!r} vs {child.manifest_version!r}; refuse and re-issue"
            )
        parent_caps = _resolve(parent.scope_tokens, parent.manifest_version)
        child_caps = _resolve(child.scope_tokens, child.manifest_version)
        if not child_caps <= parent_caps:
            raise AttenuationViolationError(
                f"{parent.subject}->{child.subject}: widened authority "
                f"{sorted(child_caps - parent_caps)}"
            )


# Observed failure: O issued under v7, W validated against v8.
chain = [
    Link("root", frozenset({"tool:filesystem:write", "net:egress:internal"}), "v7"),
    Link("orchestrator", frozenset({"tool:filesystem:write", "net:egress:internal"}), "v7"),
    Link("worker", frozenset({"tool:filesystem:write", "net:egress:internal"}), "v8"),
]
verify_chain(chain)  # raises ManifestSkewError before any authority is exercised
