# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-unsound-attenuation-in-agent-to-agent-capability-delegation-chains-with-macaroons-and-revocation-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-unsound-attenuation-in-agent-to-agent-capability-delegation-chains-with-macaroons-and-revocation-propagation.warrant.json
# Markdown SHA-256:   77f90aaeeca3f8d231d9c682755d14723dcf3069202fe427f0375e71e4b57b4f
# Code AST SHA-256:   82aafc3cf8c874b284caff44f05f565d9aada30ea7c9ca115558f7d83fcc7c8c
# Verified Classes:   DelegationInvariantError, Caveat, DelegatedCapability
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable, Mapping


class DelegationInvariantError(RuntimeError):
    """Raised when a delegated capability cannot be soundly evaluated."""


@dataclass(frozen=True)
class Caveat:
    name: str
    value: str


@dataclass
class DelegatedCapability:
    token_id: str
    caveats: tuple[Caveat, ...]
    issued_at: float
    ttl_seconds: float
    revocation_check_at: float | None = None
    revocation_cache_ttl: float = 0.0

    def remaining_lifetime(self, now: float) -> float:
        return (self.issued_at + self.ttl_seconds) - now


# A verifier semantics registry maps caveat name -> predicate.
# Predicates MUST be monotone: adding a caveat can only shrink acceptance.
# A predicate with a default-allow branch is rejected at registration.
VerifierSemantics = Mapping[str, Callable[[str, Mapping[str, str]], bool]]


def _is_monotone(predicate: Callable[[str, Mapping[str, str]], bool]) -> bool:
    # Conservative structural check: a predicate that accepts the empty
    # context has a default-allow branch and is non-monotone for our purposes.
    try:
        return not predicate("", {})
    except Exception:
        return False


def preflight_delegated_action(
    cap: DelegatedCapability,
    target_verifier_semantics: VerifierSemantics | None,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if target_verifier_semantics is None:
        raise DelegationInvariantError(
            f"capability {cap.token_id}: cannot obtain verifier caveat semantics; "
            "refusing to act on delegated authority"
        )

    for name, predicate in target_verifier_semantics.items():
        if not _is_monotone(predicate):
            raise DelegationInvariantError(
                f"capability {cap.token_id}: verifier caveat {name!r} is non-monotone "
                "(default-allow); attenuation cannot be trusted"
            )

    # Every caveat on the token must be understood by the target verifier.
    unknown = [c.name for c in cap.caveats if c.name not in target_verifier_semantics]
    if unknown:
        raise DelegationInvariantError(
            f"capability {cap.token_id}: verifier does not implement caveats {unknown}; "
            "cannot prove attenuation is respected"
        )

    # Revocation freshness: a cached satisfaction must not outlive the capability.
    if cap.revocation_check_at is not None:
        cache_age = now - cap.revocation_check_at
        effective_cache_ttl = min(cap.revocation_cache_ttl, cap.remaining_lifetime(now))
        if cache_age > effective_cache_ttl:
            raise DelegationInvariantError(
                f"capability {cap.token_id}: revocation satisfaction is stale "
                f"(age={cache_age:.1f}s, allowed={effective_cache_ttl:.1f}s); "
                "fail-closed"
            )

    if cap.remaining_lifetime(now) <= 0:
        raise DelegationInvariantError(
            f"capability {cap.token_id}: expired at preflight"
        )


def delegate_action(
    cap: DelegatedCapability,
    action: str,
    context: Mapping[str, str],
    target_verifier_semantics: VerifierSemantics | None,
    now: float | None = None,
) -> bool:
    preflight_delegated_action(cap, target_verifier_semantics, now=now)
    # Only after preflight may the delegate evaluate the action against the
    # verifier's own semantics; any caveat the verifier does not understand
    # has already caused a raise above.
    allowed = True
    for caveat in cap.caveats:
        predicate = target_verifier_semantics[caveat.name]
        if not predicate(caveat.value, context):
            allowed = False
            break
    if not allowed:
        raise DelegationInvariantError(
            f"capability {cap.token_id}: action {action!r} not authorized under "
            "verifier semantics"
        )
    return True
