# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-replay-in-aaif-delegated-credential-chains-when-a-sub-agent-re-presents-a-parent-warrant-after-token-expiry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-replay-in-aaif-delegated-credential-chains-when-a-sub-agent-re-presents-a-parent-warrant-after-token-expiry.warrant.json
# Markdown SHA-256:   cf67b41cea8c3ea753a12965f0708b3472a378f99747ff49ac1c7816ce5de752
# Code AST SHA-256:   286c971424af46f81cb5fac70904c8c00a762714c219460b8f644d3e6c28e176
# Verified Classes:   WarrantReplayError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class WarrantReplayError(RuntimeError):
    """Raised when a leaf warrant is presented past its own not_after,
    even if an ancestor warrant in the chain remains live."""


@dataclass(frozen=True)
class Warrant:
    scope: str          # e.g. "fs:read:/data/reports/q3"
    not_after: int      # epoch seconds
    parent_scope: str | None = None
    revoked: bool = False


def _scope_narrows(child: str, parent: str) -> bool:
    return child == parent or child.startswith(parent.rstrip("/") + "/")


def verify_chain(chain: Sequence[Warrant], now: int, max_depth: int = 4) -> None:
    if not chain:
        raise WarrantReplayError("empty warrant chain")
    if len(chain) > max_depth:
        raise WarrantReplayError(f"chain depth {len(chain)} exceeds max {max_depth}")

    # Structural attenuation: each hop must narrow its parent.
    for i in range(1, len(chain)):
        if not _scope_narrows(chain[i].scope, chain[i - 1].scope):
            raise WarrantReplayError(
                f"hop {i} scope {chain[i].scope!r} does not narrow {chain[i-1].scope!r}"
            )

    # Per-hop time conjunction: the leaf's expiry is authoritative.
    leaf = chain[-1]
    if now >= leaf.not_after:
        # Diagnose the specific ancestor-live / leaf-dead window.
        live_ancestors = [w for w in chain[:-1] if now < w.not_after]
        if live_ancestors:
            raise WarrantReplayError(
                f"leaf expired at {leaf.not_after} (now={now}) while "
                f"{len(live_ancestors)} ancestor(s) still live; "
                f"replay of dead leaf under live parent is forbidden"
            )
        raise WarrantReplayError(f"leaf expired at {leaf.not_after} (now={now})")

    for i, w in enumerate(chain):
        if w.revoked:
            raise WarrantReplayError(f"hop {i} revoked")
        if now >= w.not_after:
            raise WarrantReplayError(f"hop {i} expired at {w.not_after} (now={now})")


def resume_from_checkpoint(serialized_leaf: Warrant, now: int, parent_live: Warrant) -> Warrant:
    """On resume, a serialized leaf is a claim to re-verify, not to present."""
    if now >= serialized_leaf.not_after:
        # Correct behavior: re-derive a fresh leaf from the live parent.
        if now >= parent_live.not_after:
            raise WarrantReplayError("parent also expired; must re-delegate from root")
        return Warrant(
            scope=serialized_leaf.scope,
            not_after=min(now + 600, parent_live.not_after),
            parent_scope=parent_live.scope,
        )
    verify_chain([parent_live, serialized_leaf], now)
    return serialized_leaf
