# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-capability-token-after-a-mid-chain-revocation-monotonic-attenuation-loss-in-aaif-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-capability-token-after-a-mid-chain-revocation-monotonic-attenuation-loss-in-aaif-delegation-chain.warrant.json
# Markdown SHA-256:   5f2ec3e3a284c491adadafc5995413144f46e1e870b1e8b2c00906e298a4a3bf
# Code AST SHA-256:   433b4e7dcbf26d64159dad3a666f4fbb4b3f3a27169b15e97897838d985a431c
# Verified Classes:   AttenuationLossError, CapabilityToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class AttenuationLossError(RuntimeError):
    """Raised when a re-minted capability token's effective scope exceeds
    the transitive intersection of its live ancestor chain."""
    pass


@dataclass
class CapabilityToken:
    subject: str
    scope: frozenset
    parent_hash: str
    issued_at: float
    expires_at: float
    revocation_caveats: frozenset = field(default_factory=frozenset)

    def hash(self) -> str:
        payload = f"{self.subject}|{sorted(self.scope)}|{self.parent_hash}|{self.issued_at}"
        return hashlib.sha256(payload.encode()).hexdigest()

    def effective_scope(self) -> frozenset:
        return self.scope - self.revocation_caveats


def re_mint_child(
    delegator: CapabilityToken,
    prior_child_scope: frozenset,
    requested_scope: frozenset,
    ancestor_chain: list,
    now: float | None = None,
) -> CapabilityToken:
    """Re-mint a child token, enforcing monotone attenuation against the
    live ancestor chain rather than cached delegator state."""
    now = now if now is not None else time.time()

    # Condition 1: fresh ancestor fetch — recompute delegator effective scope
    # by full walk to root, honoring live revocation caveats.
    live_effective = delegator.effective_scope()
    for ancestor in ancestor_chain:
        live_effective = live_effective & ancestor.effective_scope()

    # Condition 2: narrowing predicate stability — clamp requested scope to
    # the prior child scope, never to the requester's widened ask.
    clamped = requested_scope & prior_child_scope

    # Condition 3: the re-minted scope must be a subset of live effective scope.
    if not clamped <= live_effective:
        raise AttenuationLossError(
            f"re-mint for {delegator.subject} would grant {sorted(clamped)} "
            f"exceeding live ancestor effective scope {sorted(live_effective)}; "
            f"revocation caveats active on chain: "
            f"{sorted(set().union(*[a.revocation_caveats for a in ancestor_chain]))}"
        )

    return CapabilityToken(
        subject=delegator.subject,
        scope=clamped,
        parent_hash=delegator.hash(),
        issued_at=now,
        expires_at=now + 3600,
    )


def verify_leaf(leaf: CapabilityToken, ancestor_chain: list, now: float | None = None) -> bool:
    """Leaf verifier: fast path only when no ancestor has revocation caveats
    and no renewal drift is detected; otherwise full walk."""
    now = now if now is not None else time.time()
    if now >= leaf.expires_at:
        return False

    any_revocation = any(a.revocation_caveats for a in ancestor_chain)
    renewal_drift = any(
        leaf.issued_at - a.issued_at > 3600 for a in ancestor_chain
    )

    if not any_revocation and not renewal_drift:
        # Fast path: parent hash + local subset check.
        parent = ancestor_chain[-1] if ancestor_chain else None
        return parent is not None and leaf.parent_hash == parent.hash() and leaf.scope <= parent.scope

    # Full walk: transitive intersection against live effective scopes.
    transitive = leaf.scope
    for ancestor in ancestor_chain:
        transitive = transitive & ancestor.effective_scope()
    if transitive != leaf.scope:
        raise AttenuationLossError(
            f"leaf {leaf.subject} declares {sorted(leaf.scope)} but transitive "
            f"intersection is {sorted(transitive)}; attenuation loss detected"
        )
    return True
