# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-attenuated-scope-replay-in-aaif-delegation-chains-when-the-parent-token-s-nbf-is-re-anchored-by-a-caching-verifier.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-attenuated-scope-replay-in-aaif-delegation-chains-when-the-parent-token-s-nbf-is-re-anchored-by-a-caching-verifier.warrant.json
# Markdown SHA-256:   f596e8ea4a0e7bd70e0035ef61e5acb81b2a30f33831fe69f74efbd3ac2d9977
# Code AST SHA-256:   ccc470739a3eccbd47d75a463aeaf5a4358578490997668feb6b3af1978149c6
# Verified Classes:   PosthumousChildError, SignedToken, CacheRecord
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PosthumousChildError(RuntimeError):
    """Raised when a child delegation token's validity window escapes its signed parent's window."""


@dataclass(frozen=True)
class SignedToken:
    body: bytes          # canonical signed bytes; source of truth for temporal claims
    nbf: int
    exp: int
    scope: frozenset
    parent_hash: str | None

    def digest(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


@dataclass(frozen=True)
class CacheRecord:
    """Verifier cache entry. NOTE: may carry a re-anchored nbf/exp. Never trust for containment."""
    valid: bool
    reanchored_nbf: int
    reanchored_exp: int


def admit_child(child: SignedToken, parent_signed: SignedToken,
                cache: dict[str, CacheRecord]) -> None:
    # Cache may only accelerate signature validation, never supply temporal claims.
    rec = cache.get(parent_signed.digest())
    if rec is not None and not rec.valid:
        raise PosthumousChildError("parent marked invalid in cache")

    if child.parent_hash != parent_signed.digest():
        raise PosthumousChildError("parent_hash does not match signed parent bytes")

    if not child.scope.issubset(parent_signed.scope):
        raise PosthumousChildError(f"scope escape: {child.scope - parent_signed.scope}")

    # The three containment invariants, evaluated against SIGNED bytes only.
    if child.nbf < parent_signed.nbf:
        raise PosthumousChildError(
            f"child.nbf={child.nbf} precedes parent.nbf={parent_signed.nbf}")
    if child.nbf > parent_signed.exp:
        raise PosthumousChildError(
            f"posthumous child: child.nbf={child.nbf} > parent.exp={parent_signed.exp}")
    if child.exp > parent_signed.exp:
        raise PosthumousChildError(
            f"child.exp={child.exp} exceeds parent.exp={parent_signed.exp}")


def mint_child(parent_signed: SignedToken, now: int, ttl: int,
               scope: frozenset, live_check: callable) -> SignedToken:
    # Cold-start discipline: re-validate parent liveness against signed claims,
    # not against any locally resumed or cached copy.
    if not live_check(parent_signed):
        raise PosthumousChildError(
            f"refusing to mint under parent expired at {parent_signed.exp} (now={now})")
    if now > parent_signed.exp:
        raise PosthumousChildError(
            f"mint time {now} past parent.exp {parent_signed.exp}")
    return SignedToken(
        body=b"", nbf=max(now, parent_signed.nbf),
        exp=min(now + ttl, parent_signed.exp),
        scope=scope, parent_hash=parent_signed.digest())
