# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegated-credential-chain-during-multi-hop-agent-handoff-the-depth-vs-ttl-inversion.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegated-credential-chain-during-multi-hop-agent-handoff-the-depth-vs-ttl-inversion.warrant.json
# Markdown SHA-256:   e803fb94ada9539898114966c63359ac9d67e3713c347edea17bb6a84e18b144
# Code AST SHA-256:   ecc57abd7b2970dcb48add95d72074bdbd0d299be50b70f2703a4d847f8f4c0d
# Verified Classes:   DelegatedChainInvariantError, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegatedChainInvariantError(RuntimeError):
    """Raised when a delegated credential chain violates temporal or provenance containment."""
    pass


@dataclass
class Credential:
    subject: str
    scope: frozenset
    exp: float                      # absolute epoch seconds
    act: tuple = ()                 # actor chain, oldest-first
    root_id: Optional[str] = None
    ttl_clamped: bool = False
    requested_exp: Optional[float] = None


def mint_child(parent: Credential, subject: str, scope: frozenset,
               requested_exp: float) -> Credential:
    # scope must narrow; provenance must grow by exactly one
    if not scope.issubset(parent.scope):
        raise DelegatedChainInvariantError(
            f"scope escalation: {scope} not subset of {parent.scope}")
    # THE INVARIANT: clamp expiry to parent horizon, and propagate the CLAMPED value
    clamped_exp = min(parent.exp, requested_exp)
    was_clamped = clamped_exp < requested_exp
    return Credential(
        subject=subject,
        scope=scope,
        exp=clamped_exp,
        act=parent.act + (parent.subject,),
        root_id=parent.root_id or parent.subject,
        ttl_clamped=was_clamped,
        requested_exp=requested_exp if was_clamped else None,
    )


def verify_chain(chain: list, revoked_roots: set) -> None:
    """chain[0] is root, chain[-1] is leaf. Walk full path; fail closed."""
    if not chain:
        raise DelegatedChainInvariantError("empty chain")
    root = chain[0]
    if root.root_id in revoked_roots:
        raise DelegatedChainInvariantError(f"root {root.root_id} revoked")

    min_exp = root.exp
    for depth, cred in enumerate(chain):
        # temporal containment: exp must be non-increasing with depth
        if cred.exp > min_exp + 1e-9:
            raise DelegatedChainInvariantError(
                f"temporal inversion at depth {depth}: exp {cred.exp} > ancestor min {min_exp}")
        min_exp = min(min_exp, cred.exp)
        # provenance completeness: actor chain length must equal depth
        if len(cred.act) != depth:
            raise DelegatedChainInvariantError(
                f"provenance truncation at depth {depth}: act len {len(cred.act)} != {depth}")
        # scope monotonicity
        if depth > 0 and not cred.scope.issubset(chain[depth - 1].scope):
            raise DelegatedChainInvariantError(f"scope escalation at depth {depth}")


def honor_request(chain: list, revoked_roots: set, required_scope: frozenset) -> str:
    verify_chain(chain, revoked_roots)
    leaf = chain[-1]
    if not required_scope.issubset(leaf.scope):
        raise DelegatedChainInvariantError(
            f"leaf lacks required scope {required_scope}")
    return f"granted:{leaf.subject}@depth{len(chain)-1}"
