# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-revoked-skill-manifest-that-its-own-registry-already-tombstoned.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-revoked-skill-manifest-that-its-own-registry-already-tombstoned.warrant.json
# Markdown SHA-256:   ea1991c3aed91a365993971527be0f0a4b203bc0ba384c5183427f56ff5e97b6
# Code AST SHA-256:   e4f4ffdb491917e8cae7277dacca946bbc982ac9f3451f0e797465ecb6c2c4e5
# Verified Classes:   RevocationInvariantViolation, Manifest, Revocation, Registry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class RevocationInvariantViolation(RuntimeError):
    """Raised when a skill load would execute past a known revocation."""
    pass


@dataclass
class Manifest:
    skill_id: str
    scope: str
    author_sig_valid: bool
    not_after: float
    effect_class: str  # READ_ONLY | MUTATING | EGRESS | CREDENTIAL


@dataclass
class Revocation:
    skill_id: str
    scope: str
    revoked_at: float
    operator_sig_valid: bool


@dataclass
class Registry:
    tombstones: dict = field(default_factory=dict)  # (skill_id, scope) -> revoked_at
    max_staleness: float = 90.0
    watermark: float = 0.0  # last tombstone-feed timestamp observed

    def tombstone(self, r: Revocation) -> None:
        if not r.operator_sig_valid:
            return
        key = (r.skill_id, r.scope)
        prev = self.tombstones.get(key)
        if prev is None or r.revoked_at > prev:
            self.tombstones[key] = r.revoked_at
        self.watermark = max(self.watermark, r.revoked_at)


def authorize(reg: Registry, m: Manifest, now: float,
              lease_ttl: float, checkpoint_watermark: Optional[float] = None) -> None:
    # 1. Signature and expiry are necessary but NOT sufficient.
    if not m.author_sig_valid:
        raise RevocationInvariantViolation(f"{m.skill_id}: bad author signature")
    if now >= m.not_after:
        raise RevocationInvariantViolation(f"{m.skill_id}: manifest expired")

    # 2. Lease must not outlive the revocation window for mutating effects.
    if m.effect_class != "READ_ONLY" and lease_ttl > reg.max_staleness:
        raise RevocationInvariantViolation(
            f"{m.skill_id}: lease_ttl={lease_ttl} exceeds max_staleness="
            f"{reg.max_staleness} for effect_class={m.effect_class}"
        )

    # 3. Tombstone check is a conjunct on the load path, not advisory.
    revoked_at = reg.tombstones.get((m.skill_id, m.scope))
    if revoked_at is not None and revoked_at <= now:
        raise RevocationInvariantViolation(
            f"{m.skill_id}: revoked at {revoked_at}, load attempted at {now}"
        )

    # 4. Cold-start resume must not inherit a pre-revocation cache.
    if checkpoint_watermark is not None and checkpoint_watermark < reg.watermark:
        raise RevocationInvariantViolation(
            f"{m.skill_id}: checkpoint watermark {checkpoint_watermark} "
            f"behind registry watermark {reg.watermark}; re-resolve required"
        )


# --- trace of the observed failure ---
reg = Registry()
now = 1_000_000.0
m = Manifest("repo.mutate.v3", "fs.write", True, now + 4 * 3600, "MUTATING")
reg.tombstone(Revocation("repo.mutate.v3", "fs.write", now - 90, True))

try:
    authorize(reg, m, now, lease_ttl=4 * 3600)
except RevocationInvariantViolation as e:
    print("BLOCKED:", e)
    # BLOCKED: repo.mutate.v3: lease_ttl=14400 exceeds max_staleness=90.0 ...
    # and, had TTL been short, the tombstone conjunct would also fire.
