# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-speculative-side-effects-before-its-upstream-warrant-is-sealed.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-speculative-side-effects-before-its-upstream-warrant-is-sealed.warrant.json
# Markdown SHA-256:   561441097b02f22e266a0410172a22c963878bb7a9b6b2279a77dea5a5f4ca07
# Code AST SHA-256:   2a8e76d8689de8b540dd870227f7744515c5a34a85b00df51a96b3863de4fc9a
# Verified Classes:   UnsealedWarrantError, WarrantSupersededError, Warrant, CommitLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class UnsealedWarrantError(RuntimeError):
    """Raised when an instance attempts to emit an external side effect
    against an upstream artifact that lacks a valid, sealed, non-superseded
    warrant. This is the fail-closed guard for speculative commitment."""


class WarrantSupersededError(UnsealedWarrantError):
    """Raised when the warrant was valid at receipt but has been superseded
    or revoked by the time the effect-emitting tool is invoked."""


@dataclass
class Warrant:
    artifact_hash: str
    sealed: bool
    sealed_by: str
    superseded: bool = False
    signature: Optional[str] = None

    def is_valid(self) -> bool:
        # Positive check: every condition must be affirmatively true.
        # Absence, None, or unparseable => invalid (fail-closed).
        return (
            self.sealed is True
            and self.superseded is False
            and isinstance(self.artifact_hash, str)
            and len(self.artifact_hash) == 64
            and self.signature is not None
        )


class CommitLog:
    """Single source of truth for warrant lifecycle. The sealing agent
    writes here; downstream instances read here at tool-call time."""

    def __init__(self) -> None:
        self._warrants: dict[str, Warrant] = {}

    def seal(self, artifact_hash: str, sealed_by: str, signature: str) -> None:
        self._warrants[artifact_hash] = Warrant(
            artifact_hash=artifact_hash,
            sealed=True,
            sealed_by=sealed_by,
            signature=signature,
        )

    def supersede(self, artifact_hash: str) -> None:
        if artifact_hash in self._warrants:
            self._warrants[artifact_hash].superseded = True

    def get(self, artifact_hash: str) -> Optional[Warrant]:
        return self._warrants.get(artifact_hash)


def emit_effect(
    artifact: dict,
    commit_log: CommitLog,
    idempotency_key: str,
    effect_fn,
) -> None:
    """Emit an external side effect ONLY against a call-time-valid warrant.

    Re-reads warrant state at invocation time (not receipt time) so that
    supersession landing between message receipt and tool call is caught.
    """
    artifact_hash = hashlib.sha256(
        repr(sorted(artifact.items())).encode()
    ).hexdigest()

    warrant = commit_log.get(artifact_hash)

    if warrant is None:
        raise UnsealedWarrantError(
            f"No warrant exists for artifact {artifact_hash[:12]}; "
            f"speculation may not become effect."
        )

    if not warrant.is_valid():
        # Distinguish supersession for reconciliation tooling.
        if warrant.superseded:
            raise WarrantSupersededError(
                f"Warrant for {artifact_hash[:12]} was superseded before "
                f"effect emission; effect deferred and must be reconciled "
                f"under key {idempotency_key}."
            )
        raise UnsealedWarrantError(
            f"Warrant for {artifact_hash[:12]} is not sealed/valid "
            f"(sealed={warrant.sealed!r}, sig={warrant.signature!r}); "
            f"fail-closed."
        )

    # Only now, with a call-time-valid sealed warrant, do we touch the world.
    effect_fn(idempotency_key=idempotency_key, artifact=artifact)
