# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-continues-executing-under-a-revoked-warrant-across-an-aaif-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-continues-executing-under-a-revoked-warrant-across-an-aaif-trust-boundary.warrant.json
# Markdown SHA-256:   616acede0c02fdf0fafe461e9661233a123579958ba467df2c3ea57082a44abc
# Code AST SHA-256:   add19ba076f4c94f4b4f6809826a5e1826b1453235788a54807279aa717b81f7
# Verified Classes:   RevocationStalenessError, Warrant, Chain, Executor
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class RevocationStalenessError(RuntimeError):
    """Raised when an action would be taken on a chain whose root authority
    freshness cannot be confirmed within the action's reversal budget."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    scope: frozenset
    issued_at: float
    expires_at: float
    max_staleness: Optional[float]          # seconds; None == unbounded validity
    revocation_endpoint: Optional[str]      # None == no live channel


@dataclass(frozen=True)
class Chain:
    hops: tuple            # ordered issuer -> ... -> leaf
    last_root_signature: float


def bind_executor(chain: Chain, action_reversibility: str,
                  now: Optional[float] = None) -> "Executor":
    now = time.time() if now is None else now
    leaf = chain.hops[-1]
    root = chain.hops[0]

    if now >= leaf.expires_at:
        raise RevocationStalenessError(
            f"leaf warrant expired at {leaf.expires_at:.0f}; refusing bind"
        )

    if action_reversibility == "strict":
        if leaf.max_staleness is None:
            raise RevocationStalenessError(
                f"strict-reversibility deployment bound to warrant from "
                f"{root.issuer} with no max_staleness; revocation latency is "
                f"unbounded (up to TTL {leaf.expires_at - now:.0f}s). Refusing."
            )
        age = now - chain.last_root_signature
        if age > leaf.max_staleness:
            raise RevocationStalenessError(
                f"root signature age {age:.0f}s exceeds max_staleness "
                f"{leaf.max_staleness:.0f}s; authority freshness unconfirmed"
            )
        if leaf.revocation_endpoint is None:
            raise RevocationStalenessError(
                f"strict-reversibility deployment requires a revocation "
                f"endpoint on the leaf warrant; none present. A signed chain "
                f"without a revocation channel is a bearer token."
            )

    return Executor(chain=chain, bound_at=now,
                    reversal_budget=leaf.max_staleness or 0.0)


class Executor:
    def __init__(self, chain: Chain, bound_at: float, reversal_budget: float):
        self.chain = chain
        self.bound_at = bound_at
        self.reversal_budget = reversal_budget

    def execute(self, action: str, irreversible: bool,
                revocation_check_passed: bool, now: Optional[float] = None) -> str:
        now = time.time() if now is None else now
        leaf = self.chain.hops[-1]

        if now >= leaf.expires_at:
            raise RevocationStalenessError(
                f"warrant expired mid-execution at {leaf.expires_at:.0f}"
            )

        if irreversible and not revocation_check_passed:
            # Fail closed for irreversible actions on unconfirmed authority.
            raise RevocationStalenessError(
                f"refusing irreversible action {action!r}: revocation state "
                f"unconfirmed and reversal_budget={self.reversal_budget:.0f}s "
                f"cannot absorb a late revocation discovery"
            )

        age = now - self.chain.last_root_signature
        if leaf.max_staleness is not None and age > leaf.max_staleness:
            raise RevocationStalenessError(
                f"root signature stale by {age:.0f}s > "
                f"{leaf.max_staleness:.0f}s at action {action!r}"
            )

        return f"executed:{action}@age={age:.0f}s"


# Reproduce the observed failure as a test: a chain with no max_staleness
# and no revocation endpoint, bound under a strict-reversibility policy,
# must be rejected at bind time, not discovered 780s later.
if __name__ == "__main__":
    now = 1_000_000.0
    w_root = Warrant("root-orchestrator", frozenset({"read:repo", "exec:tests"}),
                     now, now + 3600, max_staleness=None,
                     revocation_endpoint=None)
    w_leaf = Warrant("planner", frozenset({"exec:tests"}),
                     now, now + 900, max_staleness=None,
                     revocation_endpoint=None)
    chain = Chain(hops=(w_root, w_leaf), last_root_signature=now)

    try:
        bind_executor(chain, action_reversibility="strict", now=now)
        raise AssertionError("expected bind to fail closed")
    except RevocationStalenessError as e:
        print(f"correctly refused at bind: {e}")
