# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-downgrade-as-a-revocation-event-rather-than-a-stale-cache-miss.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-downgrade-as-a-revocation-event-rather-than-a-stale-cache-miss.warrant.json
# Markdown SHA-256:   8d5b58d9693ef7320d9201dac241d5fd57b39df3c36820ef5c54b7ffb68a1b5c
# Code AST SHA-256:   efc17a1f024fa69ce4ee9d8c6388e73887c2ebbbaed3e1ebad21ed23b511aafb
# Verified Classes:   CapabilityDowngradeViolation, PrecedenceUnprovable, Scope, Warrant, CapabilityCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class CapabilityDowngradeViolation(RuntimeError):
    """Raised when an instance exercises a capability that a causally-newer
    downgrade has already revoked, or when it cannot prove precedence and
    attempts a mutating call inside the unproven window."""


class PrecedenceUnprovable(CapabilityDowngradeViolation):
    """Raised when a downgrade arrives without a precedence witness and the
    quarantine window has expired while a mutating call is pending."""


@dataclass(frozen=True)
class Scope:
    tools: frozenset

    def is_strict_subset_of(self, other: "Scope") -> bool:
        return self.tools < other.tools


@dataclass(frozen=True)
class Warrant:
    subject: str
    resource: str
    issuer: str
    scope: Scope
    issued_at: float
    epoch: int


@dataclass
class CapabilityCache:
    # Keyed on (subject, resource, issuer) — NOT on token bytes.
    held: dict = field(default_factory=dict)
    authoritative: dict = field(default_factory=dict)
    quarantine_until: dict = field(default_factory=dict)

    def effective_scope(self, subject: str, resource: str, issuer: str) -> Scope:
        key = (subject, resource, issuer)
        held = self.held.get(key)
        auth = self.authoritative.get(key)
        if held is None:
            raise CapabilityDowngradeViolation(f"no held warrant for {key}")
        if auth is None:
            return held.scope
        # Intersection: the downgrade revokes the superset even if the
        # held token bytes are unchanged.
        return Scope(tools=held.scope.tools & auth.scope.tools)

    def apply_downgrade(self, new: Warrant, now: float) -> None:
        key = (new.subject, new.resource, new.issuer)
        held = self.held.get(key)
        if held is None:
            # Nothing to downgrade; record authoritative intent.
            self.authoritative[key] = new
            return
        if new.issuer != held.issuer:
            # Regime 3: competing issuer -> conflict resolution, do not act.
            raise CapabilityDowngradeViolation(
                f"downgrade issuer {new.issuer} != held issuer {held.issuer}"
            )
        if not new.scope.is_strict_subset_of(held.scope):
            # Not a downgrade (wider/disjoint). Do not self-revoke.
            raise CapabilityDowngradeViolation(
                f"non-narrowing re-issue for {key}: {new.scope} vs {held.scope}"
            )
        # Precedence: epoch is the witness. If absent or older, quarantine.
        if new.epoch > held.epoch:
            self.authoritative[key] = new
            self.quarantine_until.pop(key, None)
        else:
            # Regime 2: cannot prove newer -> bounded quarantine.
            self.quarantine_until[key] = now + QUARANTINE_WINDOW_S

    def check_call(self, subject: str, resource: str, issuer: str,
                   tool: str, now: float) -> None:
        key = (subject, resource, issuer)
        if now < self.quarantine_until.get(key, 0.0):
            if tool in MUTATING_TOOLS:
                raise PrecedenceUnprovable(
                    f"mutating call {tool!r} blocked in quarantine for {key}"
                )
            return
        if tool not in self.effective_scope(subject, resource, issuer).tools:
            raise CapabilityDowngradeViolation(
                f"tool {tool!r} not in effective scope for {key}"
            )


QUARANTINE_WINDOW_S = 120.0  # p99 of measured propagation latency, re-measured
MUTATING_TOOLS = frozenset({"write", "exec", "delete"})
