# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-agent-consensus-as-an-agreement-problem-over-committed-intent-rather-than-over-reported-state-and-w.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-agent-consensus-as-an-agreement-problem-over-committed-intent-rather-than-over-reported-state-and-w.warrant.json
# Markdown SHA-256:   a3a1ec076ef01cf5d65a42cb3947983dd96d66ad6228b75789da5314d3a9e61f
# Code AST SHA-256:   48d7202ca1f290e6382defe946890030e67098abc6fd8bb793bf3c6bff7f1db0
# Verified Classes:   CommitInvariantViolation, Intent, IntentAgreementLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Set


class CommitInvariantViolation(RuntimeError):
    """Raised when an agent attempts to apply or certify an effect that
    violates the intent-agreement invariant (at-most-once execution)."""
    pass


@dataclass(frozen=True)
class Intent:
    task_id: str
    epoch: int
    will_not_reexecute: bool = True

    def key(self) -> str:
        return hashlib.sha256(
            f"{self.task_id}:{self.epoch}".encode()
        ).hexdigest()


class IntentAgreementLog:
    """Durable intent log + certificate store. Lives outside the context
    window; keyed by (task_id, epoch). Enforces at-most-once execution."""

    def __init__(self, quorum: int):
        self.quorum = quorum
        self._intents: Dict[str, Intent] = {}
        self._certs: Dict[str, Set[str]] = {}          # key -> signer ids
        self._applied: Set[str] = set()                # keys already effected

    def record_intent(self, agent_id: str, intent: Intent) -> None:
        if not intent.will_not_reexecute:
            raise CommitInvariantViolation(
                f"intent {intent.key()} does not promise non-reexecution"
            )
        self._intents[intent.key()] = intent
        self._certs.setdefault(intent.key(), set()).add(agent_id)

    def sign_certificate(self, agent_id: str, task_id: str, epoch: int) -> None:
        key = Intent(task_id, epoch).key()
        # Strict equality: a signer may only certify an intent it has
        # itself durably recorded. No stale-epoch relaxation (>=).
        if key not in self._intents:
            raise CommitInvariantViolation(
                f"agent {agent_id} signing {key} without a recorded intent "
                f"(stale or fabricated observation)"
            )
        self._certs[key].add(agent_id)

    def is_certified(self, task_id: str, epoch: int) -> bool:
        key = Intent(task_id, epoch).key()
        return len(self._certs.get(key, set())) >= self.quorum

    def apply_effect(self, task_id: str, epoch: int) -> None:
        key = Intent(task_id, epoch).key()
        if not self.is_certified(task_id, epoch):
            raise CommitInvariantViolation(
                f"refusing to apply {key}: no quorum certificate "
                f"({len(self._certs.get(key, set()))}/{self.quorum})"
            )
        if key in self._applied:
            raise CommitInvariantViolation(
                f"double execution of {key}: effect already applied"
            )
        self._applied.add(key)

    def resume_after_cold_start(self, task_id: str, epoch: int) -> str:
        key = Intent(task_id, epoch).key()
        if key in self._intents and not self.is_certified(task_id, epoch):
            # Intent exists but certificate was lost to context truncation.
            # Must abort and re-negotiate, never re-execute.
            raise CommitInvariantViolation(
                f"resume found intent {key} without certificate; "
                f"abort and renegotiate instead of re-executing"
            )
        return "applied" if key in self._applied else "pending"
