# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-its-delegated-scope-when-a-verifiable-credential-s-attenuation-chain-is-valid-but-its-capability-attestation-has-expi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-its-delegated-scope-when-a-verifiable-credential-s-attenuation-chain-is-valid-but-its-capability-attestation-has-expi.warrant.json
# Markdown SHA-256:   59e492152ed8b505bfdad91aea986d9434eabf433c44597dbdb5d9fba3e3c65f
# Code AST SHA-256:   f5057ba2af7eabe30aeec60d00b060afd380654958ab13dca039e990f56a38c3
# Verified Classes:   AttestationStaleError, VerifiableCredential, CapabilityAttestation, Runtime
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationStaleError(RuntimeError):
    """Raised when a delegated scope is presented without a live, runtime-matching
    capability attestation at the moment of a side-effecting tool call."""


@dataclass(frozen=True)
class VerifiableCredential:
    scope: frozenset
    valid_until: float
    signature_ok: bool
    attenuation_ok: bool


@dataclass(frozen=True)
class CapabilityAttestation:
    runtime_hash: str
    tool_surface_digest: str
    model_id: str
    valid_until: float
    signature_ok: bool


@dataclass(frozen=True)
class Runtime:
    runtime_hash: str
    tool_surface_digest: str
    model_id: str


SIDE_EFFECTING = {"write_", "delete_", "send_", "transfer_"}


def _is_side_effecting(tool_name: str) -> bool:
    return any(tool_name.startswith(p) for p in SIDE_EFFECTING)


def executable(
    vc: VerifiableCredential,
    att: CapabilityAttestation,
    runtime: Runtime,
    tool_name: str,
    now: float,
) -> bool:
    vc_ok = (
        vc.signature_ok
        and vc.attenuation_ok
        and now < vc.valid_until
        and any(tool_name.startswith(s) or s == "*" for s in vc.scope)
    )
    att_ok = (
        att.signature_ok
        and now < att.valid_until
        and att.runtime_hash == runtime.runtime_hash
        and att.tool_surface_digest == runtime.tool_surface_digest
        and att.model_id == runtime.model_id
    )
    return vc_ok and att_ok


def guarded_call(
    vc: VerifiableCredential,
    att: CapabilityAttestation,
    runtime: Runtime,
    tool_name: str,
    now: float,
    fetch_fresh_attestation,
) -> str:
    if _is_side_effecting(tool_name) and not executable(vc, att, runtime, tool_name, now):
        # Attempt one re-attestation before failing closed.
        fresh = fetch_fresh_attestation(runtime)
        if fresh is None or not executable(vc, fresh, runtime, tool_name, now):
            raise AttestationStaleError(
                f"side-effecting call {tool_name!r} at t={now:.0f} has no live "
                f"attestation matching runtime {runtime.runtime_hash[:8]}; "
                f"vc.valid_until={vc.valid_until:.0f}, att.valid_until={att.valid_until:.0f}"
            )
        att = fresh
    return f"executed {tool_name} under vc+att at t={now:.0f}"


# Observed failure reproduction: attestation expired at T+900, VC valid to T+3600,
# runtime tool surface drifted at T+1200, worker kept calling write_ticket.
if __name__ == "__main__":
    runtime = Runtime("rh_v2", "tsd_B", "model-x")
    vc = VerifiableCredential(
        scope=frozenset({"read_kb", "write_ticket"}),
        valid_until=3600.0,
        signature_ok=True,
        attenuation_ok=True,
    )
    stale_att = CapabilityAttestation(
        runtime_hash="rh_v1",
        tool_surface_digest="tsd_A",
        model_id="model-x",
        valid_until=900.0,
        signature_ok=True,
    )
    try:
        guarded_call(vc, stale_att, runtime, "write_ticket", now=1500.0,
                     fetch_fresh_attestation=lambda r: None)
    except AttestationStaleError as e:
        print(f"FAIL-CLOSED: {e}")
