# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-forgery-in-a-delegated-aaif-credential-chain-when-the-parent-warrant-is-re-issued-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-forgery-in-a-delegated-aaif-credential-chain-when-the-parent-warrant-is-re-issued-mid-handoff.warrant.json
# Markdown SHA-256:   d53a739ca832805b52e4c9f8fa4df196442cde5225624726f81b751e95d93b7d
# Code AST SHA-256:   cc14e759661b658e572cec8a82169a23be21bf67d17a93a78e1e1569d74a0f35
# Verified Classes:   StaleWarrantChainError, Warrant, LineageHead, WarrantStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleWarrantChainError(RuntimeError):
    """Raised when a delegated warrant's ancestor lineage head has moved
    past the epoch recorded in the child chain, and the child's scope is
    not contained in the live head's scope (partial-containment regime)."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    epoch: int
    scope: frozenset
    parent_id: Optional[str]
    issuer: str
    subject: str
    resource: str


@dataclass(frozen=True)
class LineageHead:
    epoch: int
    scope: frozenset


class WarrantStore:
    """Replay index resolves any epoch; head index resolves only the live head."""

    def __init__(self):
        self._replay: dict[str, dict[int, Warrant]] = {}
        self._head: dict[tuple, LineageHead] = {}

    def record(self, w: Warrant, live: bool = True):
        self._replay.setdefault(w.warrant_id, {})[w.epoch] = w
        if live:
            key = (w.issuer, w.subject, w.resource)
            cur = self._head.get(key)
            if cur is None or w.epoch > cur.epoch:
                self._head[key] = LineageHead(w.epoch, w.scope)

    def resolve_epoch(self, warrant_id: str, epoch: int) -> Warrant:
        return self._replay[warrant_id][epoch]

    def current_head(self, w: Warrant) -> LineageHead:
        return self._head[(w.issuer, w.subject, w.resource)]


def admit_delegated(child: Warrant, store: WarrantStore) -> None:
    """Admission gate for a downstream agent receiving a delegated warrant.

    Structural containment is necessary but NOT sufficient; we must also
    verify chain continuity against live lineage heads.
    """
    # Walk the recorded ancestor chain (child -> ... -> root).
    chain = [child]
    cursor = child
    while cursor.parent_id is not None:
        parent = store.resolve_epoch(cursor.parent_id, cursor.epoch)
        chain.append(parent)
        cursor = parent

    for ancestor in chain:
        head = store.current_head(ancestor)
        if ancestor.epoch == head.epoch:
            continue  # live, exact
        if ancestor.epoch > head.epoch:
            raise StaleWarrantChainError(
                f"epoch inversion: ancestor {ancestor.warrant_id}@{ancestor.epoch} "
                f"ahead of live head @{head.epoch}; store partition suspected"
            )
        # ancestor.epoch < head.epoch: stale. Check if child scope survives narrowing.
        if not child.scope.issubset(head.scope):
            revoked = child.scope - head.scope
            raise StaleWarrantChainError(
                f"stale chain: ancestor {ancestor.warrant_id}@{ancestor.epoch} "
                f"superseded by head @{head.epoch}; child retains revoked scope {sorted(revoked)}"
            )
        # else: benign staleness (widening-only or child scope fully survives); admit.

# Trigger trace:
store = WarrantStore()
w_o_old = Warrant("W_O", 7, frozenset({"read:repo", "write:branch/*"}), None, "O", "A", "repo")
store.record(w_o_old, live=True)                       # epoch 7 is head
w_a = Warrant("W_A", 7, frozenset({"read:repo"}), "W_O", "A", "B", "repo")
store.record(w_a, live=True)
# Mid-handoff: O re-issues, narrowing scope. epoch 8 becomes head.
w_o_new = Warrant("W_O", 8, frozenset({"read:repo/sub"}), None, "O", "A", "repo")
store.record(w_o_new, live=True)

# B admits the in-flight W_A. Structural check passes; continuity check must fire.
admit_delegated(w_a, store)   # raises StaleWarrantChainError: read:repo not ⊆ read:repo/sub
