# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegation-receipt-from-silently-outliving-the-authority-that-issued-it.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegation-receipt-from-silently-outliving-the-authority-that-issued-it.warrant.json
# Markdown SHA-256:   cb1351731c442bc093213e465a0bde99347fff9c6a6b5cec9527f12f74c41357
# Code AST SHA-256:   d1d7710dd0c007457179364898982caac2989a087277c1230b299a1cea4c91e3
# Verified Classes:   StaleDelegationReceipt, Receipt, ChainWitness, ExecutionRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Callable, Optional


class StaleDelegationReceipt(RuntimeError):
    """Raised when an execution record's chain-state witness is older than the
    freshness bound, or when the chain was revoked at execution time."""
    pass


@dataclass(frozen=True)
class Receipt:
    issuer: str
    worker: str
    principal: str
    capability: str
    resource: str
    t_issue: float
    ttl: float
    chain_ref: str  # hash of chain state at issuance (lower bound only)


@dataclass(frozen=True)
class ChainWitness:
    chain_hash: str
    revoked: bool
    t_witness: float


@dataclass(frozen=True)
class ExecutionRecord:
    receipt: Receipt
    witness: ChainWitness
    tool_call: str
    result: str
    t_exec: float


def execute_with_freshness_gate(
    receipt: Receipt,
    tool_call: str,
    fetch_chain_state: Callable[[], ChainWitness],
    epsilon: float,
    ttl_slack: float = 0.0,
) -> ExecutionRecord:
    """Worker-side gate. Refuses to execute without a fresh, unrevoked witness."""
    now = time.time()

    if now > receipt.t_issue + receipt.ttl + ttl_slack:
        raise StaleDelegationReceipt(
            f"receipt expired before execution: now={now:.1f} "
            f"expiry={receipt.t_issue + receipt.ttl:.1f}"
        )

    witness = fetch_chain_state()

    # THE INVARIANT: witness must be fresh enough that revocation cannot have
    # occurred unseen between witness fetch and execution.
    if now - witness.t_witness > epsilon:
        raise StaleDelegationReceipt(
            f"chain witness too old: age={now - witness.t_witness:.1f}s "
            f"epsilon={epsilon:.1f}s"
        )

    if witness.revoked:
        raise StaleDelegationReceipt(
            f"authority revoked at t={witness.t_witness:.1f}; "
            f"receipt chain_ref={receipt.chain_ref} is stale"
        )

    # Execute and embed the witness so the trail carries execution-time proof.
    result = f"executed:{tool_call}"
    return ExecutionRecord(
        receipt=receipt,
        witness=witness,
        tool_call=tool_call,
        result=result,
        t_exec=now,
    )


def verify_for_non_repudiation(
    record: ExecutionRecord,
    fetch_chain_state_at: Callable[[float], ChainWitness],
    epsilon: float,
) -> bool:
    """Auditor-side re-check. Signatures alone are insufficient; the chain must
    be shown unrevoked at t_exec, not merely at t_issue."""
    r = record.receipt
    if not (r.t_issue <= record.t_exec <= r.t_issue + r.ttl):
        raise StaleDelegationReceipt(
            f"execution outside delegation window: t_exec={record.t_exec:.1f}"
        )

    if abs(record.witness.t_witness - record.t_exec) > epsilon:
        raise StaleDelegationReceipt(
            "execution record lacks a freshness-bound chain witness; "
            "trail is signed but not non-repudiable"
        )

    chain_at_exec = fetch_chain_state_at(record.t_exec)
    if chain_at_exec.revoked:
        raise StaleDelegationReceipt(
            f"authority was revoked at t_exec={record.t_exec:.1f}; "
            f"record must be excluded from the audit trail"
        )

    if chain_at_exec.chain_hash != record.witness.chain_hash:
        raise StaleDelegationReceipt(
            "chain hash mismatch between witness and replayed state; "
            "possible forked authority chain"
        )

    return True
