# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-aaif-attestation-chain-when-every-hop-validates-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-aaif-attestation-chain-when-every-hop-validates-locally.warrant.json
# Markdown SHA-256:   003382f3625a949608b68dcf4eb4fd0fa1a1079634804435533d0d9546147f1a
# Code AST SHA-256:   9c84131dff3c5755ddb816c9885d716ff70f124ad4242cd9e17fce6b05a7d1db
# Verified Classes:   AttestationChainError, Attestation
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class AttestationChainError(RuntimeError):
    """Raised when an AAIF delegation chain fails structural verification."""


@dataclass
class Attestation:
    iss: str
    aud: str
    scope: frozenset
    exp: int
    parent_hash: str | None
    jti: str
    canonical_body: dict = field(default_factory=dict)

    def canonical_hash(self) -> str:
        body = {
            "iss": self.iss,
            "aud": self.aud,
            "scope": sorted(self.scope),
            "exp": self.exp,
            "parent_hash": self.parent_hash,
            "jti": self.jti,
        }
        blob = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
        return hashlib.sha256(blob).hexdigest()


def verify_chain(chain: list[Attestation], trusted_roots: set[str]) -> frozenset:
    if not chain:
        raise AttestationChainError("empty chain: no root attestation present")

    root = chain[0]
    if root.parent_hash is not None:
        raise AttestationChainError(
            f"root token {root.jti} declares a parent_hash; chain is truncated"
        )
    if root.iss not in trusted_roots:
        raise AttestationChainError(
            f"root issuer {root.iss!r} not in trust store {sorted(trusted_roots)}"
        )

    effective_scope = set(root.scope)

    for parent, child in zip(chain, chain[1:]):
        expected_parent_hash = parent.canonical_hash()
        if child.parent_hash != expected_parent_hash:
            raise AttestationChainError(
                f"parent_hash mismatch at {child.jti}: "
                f"declared={child.parent_hash!r} computed={expected_parent_hash!r} "
                f"(cross-branch replay or tampered lineage)"
            )
        if child.iss != parent.aud:
            raise AttestationChainError(
                f"audience/issuer discontinuity: parent.aud={parent.aud!r} "
                f"child.iss={child.iss!r}"
            )
        if child.exp > parent.exp:
            raise AttestationChainError(
                f"child {child.jti} outlives parent {parent.jti}"
            )
        widened = child.scope - parent.scope
        if widened:
            raise AttestationChainError(
                f"scope widening at {child.jti}: {sorted(widened)} not granted by "
                f"parent {parent.jti}"
            )
        effective_scope &= child.scope

    return frozenset(effective_scope)


def execute_tool(tool: str, required_scope: str, chain: list[Attestation],
                 trusted_roots: set[str]) -> None:
    try:
        granted = verify_chain(chain, trusted_roots)
    except AttestationChainError:
        raise
    if required_scope not in granted:
        raise AttestationChainError(
            f"tool {tool!r} requires {required_scope!r}; effective chain grant is "
            f"{sorted(granted)}"
        )
    # ... dispatch to sandboxed tool runner with `granted` as the authority set
