# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-boundary-be-enforced-in-aaif-compliant-agent-identity-revocation-and-delegation-chain-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-boundary-be-enforced-in-aaif-compliant-agent-identity-revocation-and-delegation-chain-verification.warrant.json
# Markdown SHA-256:   ed7566ff0baffaeeabd18bd243acb1ba5a909b1af753b949fbe2ec18ca334973
# Code AST SHA-256:   3284c335ea099e85788f2f42e0b56c92fc5f415c8cde3e74c4b010e70f46809d
# Verified Classes:   DelegationChainRevoked, Revocation, Node
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationChainRevoked(RuntimeError):
    """Raised when a delegation chain fails the instance-boundary invariant."""
    pass


@dataclass(frozen=True)
class Revocation:
    subject: str
    instance: Optional[str]   # None => identity-scoped
    epoch: int


@dataclass(frozen=True)
class Node:
    subject: str
    instance: str
    epoch: int


def verify_chain(
    chain: list[Node],
    revocations: list[Revocation],
    liveness: dict[tuple[str, str], int],  # (subject, instance) -> epoch seen live
    max_staleness_epoch: int,
    current_epoch: int,
) -> bool:
    if current_epoch - max_staleness_epoch > 0 and not revocations:
        # Cannot prove currency; fail closed rather than accept blindly.
        raise DelegationChainRevoked(
            f"no revocation data within staleness window "
            f"(current_epoch={current_epoch}, max_staleness_epoch={max_staleness_epoch})"
        )

    for node in chain:
        # Identity revocation dominates every instance, regardless of liveness.
        identity_dead = any(
            r.subject == node.subject
            and r.instance is None
            and r.epoch >= node.epoch
            for r in revocations
        )
        if identity_dead:
            raise DelegationChainRevoked(
                f"identity revocation dominates instance {node.instance} "
                f"at epoch {node.epoch}"
            )

        # Instance-scoped revocation kills only the bound instance.
        instance_dead = any(
            r.subject == node.subject
            and r.instance == node.instance
            and r.epoch >= node.epoch
            for r in revocations
        )
        if instance_dead:
            raise DelegationChainRevoked(
                f"instance-scoped revocation of {node.instance} at epoch {node.epoch}"
            )

        # Liveness must be proven and current; unknown is not live.
        seen = liveness.get((node.subject, node.instance))
        if seen is None or seen < node.epoch:
            raise DelegationChainRevoked(
                f"instance {node.instance} liveness unproven or stale "
                f"(seen={seen}, required>={node.epoch})"
            )

    return True
