# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-delegation-when-a-scoped-token-s-revocation-epoch-advances-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-delegation-when-a-scoped-token-s-revocation-epoch-advances-mid-tool-call.warrant.json
# Markdown SHA-256:   6190dc117f277fd64971dd9965c82e0598398ecf1c6fc8767c6b91f012226144
# Code AST SHA-256:   1b29b2ca75a1395d46cd95e162ebcee8a55e009068cc5d79c1fa3658fb5ba1a1
# Verified Classes:   RevocationEpochAdvanced, StaleArtifactQuarantined, ScopedToken, DerivedArtifact, Authority, AgentInstance
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class RevocationEpochAdvanced(RuntimeError):
    """Raised when a scope's revocation epoch advances between presentation and effect commit."""


class StaleArtifactQuarantined(RuntimeError):
    """Raised when a derived artifact is retrieved under a scope whose epoch has since advanced."""


@dataclass(frozen=True)
class ScopedToken:
    subject: str
    scope: str
    revocation_epoch: int
    exp: int


@dataclass
class DerivedArtifact:
    payload: str
    produced_under_scope: str
    epoch_at_read: int


@dataclass
class Authority:
    # Monotonic epoch per scope. Advancing this is how revocation propagates.
    epochs: dict[str, int] = field(default_factory=dict)

    def current_epoch(self, scope: str) -> int:
        return self.epochs.get(scope, 0)

    def revoke(self, scope: str) -> None:
        self.epochs[scope] = self.current_epoch(scope) + 1


@dataclass
class AgentInstance:
    token: ScopedToken
    authority: Authority
    shared_store: dict[str, DerivedArtifact] = field(default_factory=dict)

    def _probe_epoch_uncached(self) -> int:
        # Deliberately no cache: the commit gate must see the live epoch.
        return self.authority.current_epoch(self.token.scope)

    def read_ephemeral(self, key: str) -> str:
        # Ephemeral read: entry validation is sufficient; result is discarded in-turn.
        if self._probe_epoch_uncached() != self.token.revocation_epoch:
            raise RevocationEpochAdvanced(
                f"scope {self.token.scope} epoch advanced before read of {key}"
            )
        return f"content-of-{key}"

    def commit_derived(self, key: str, payload: str) -> DerivedArtifact:
        # Effectful commit: MUST re-probe epoch uncached immediately before the effect.
        live_epoch = self._probe_epoch_uncached()
        if live_epoch != self.token.revocation_epoch:
            raise RevocationEpochAdvanced(
                f"refusing to commit {key}: scope {self.token.scope} "
                f"epoch {self.token.revocation_epoch} -> {live_epoch} advanced mid-turn"
            )
        artifact = DerivedArtifact(
            payload=payload,
            produced_under_scope=self.token.scope,
            epoch_at_read=self.token.revocation_epoch,
        )
        self.shared_store[key] = artifact
        return artifact

    def retrieve(self, key: str) -> DerivedArtifact:
        # Transitive enforcement: consumer checks producer's epoch is still current.
        artifact = self.shared_store[key]
        live_epoch = self.authority.current_epoch(artifact.produced_under_scope)
        if live_epoch != artifact.epoch_at_read:
            raise StaleArtifactQuarantined(
                f"artifact {key} produced under {artifact.produced_under_scope} "
                f"at epoch {artifact.epoch_at_read}, now {live_epoch}; quarantined"
            )
        return artifact


def run_worker_turn(worker: AgentInstance, key: str) -> Optional[DerivedArtifact]:
    # Step 1: ephemeral read (entry-validated, acceptable).
    content = worker.read_ephemeral(key)
    # Step 2: an auditor revokes the scope between read and commit.
    worker.authority.revoke(worker.token.scope)
    # Step 3: commit gate fires.
    try:
        return worker.commit_derived(f"summary:{key}", f"summarized:{content}")
    except RevocationEpochAdvanced as exc:
        # Instance must drain, not silently stop: signal parent for reconciliation.
        print(f"[drain-signal] {exc}")
        raise
