# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-loses-its-delegated-capability-attestation-mid-flight-across-organizational-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-loses-its-delegated-capability-attestation-mid-flight-across-organizational-boundaries.warrant.json
# Markdown SHA-256:   843775a42de9a0baf2e60f175b15d583cd776cbc1557c06e35a0ec1274c1f197
# Code AST SHA-256:   55ba919bde1fcb7707d4a01096f0af6aa34e8188d2f036764932234dc6681df5
# Verified Classes:   DelegationWindowViolated, Attestation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationWindowViolated(RuntimeError):
    """Raised when a cross-org operation would commit past the safe authority window."""


@dataclass(frozen=True)
class Attestation:
    subject: str
    scope: str
    issued_at: float
    ttl: float
    revocation_sla: float

    def residual_validity(self, now: float) -> float:
        # Usable authority is not the TTL; it is what remains after issuance age.
        return (self.issued_at + self.ttl) - now

    def safe_commit_deadline(self, now: float, clock_skew: float) -> float:
        # Latest wall-clock time at which a commit is still soundly authorized.
        # Must leave room for revocation propagation and skew.
        return now + self.residual_validity(now) - self.revocation_sla - clock_skew


def assert_commit_within_authority(
    att: Attestation,
    operation_duration: float,
    now: float,
    clock_skew: float = 2.0,
) -> None:
    """Gate a commit on the *commit* boundary, not the admission boundary.

    Raises DelegationWindowViolated if the operation cannot complete
    before the attestation's authority is no longer sound.
    """
    deadline = att.safe_commit_deadline(now, clock_skew)
    projected_commit = now + operation_duration
    if projected_commit > deadline:
        raise DelegationWindowViolated(
            f"subject={att.subject!r} scope={att.scope!r} "
            f"projected_commit={projected_commit:.1f} "
            f"deadline={deadline:.1f} "
            f"residual={att.residual_validity(now):.1f} "
            f"revocation_sla={att.revocation_sla:.1f} "
            f"skew={clock_skew:.1f}: operation would commit outside "
            f"the sound authority window; decompose into per-step "
            f"attestations or abort."
        )


def run_delegated_step(att: Attestation, step_duration: float) -> None:
    now = time.time()
    # Re-validate at the commit boundary of each step, never cache admission.
    assert_commit_within_authority(att, step_duration, now)
    _commit(step_duration)


def _commit(step_duration: float) -> None:
    time.sleep(step_duration)  # stand-in for the durable side effect


if __name__ == "__main__":
    # Attestation issued 240s ago, 300s TTL, 60s revocation SLA.
    # Residual = 60s; sound window is negative -> must not admit.
    stale = Attestation(
        subject="agent://orgA/worker-7",
        scope="ledger:write",
        issued_at=time.time() - 240,
        ttl=300,
        revocation_sla=60,
    )
    try:
        run_delegated_step(stale, step_duration=5.0)
    except DelegationWindowViolated as exc:
        print(f"denied: {exc}")
