# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-plan-quorum-it-can-no-longer-verify-byzantine-plan-commitment-under-partial-evidence-decay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-plan-quorum-it-can-no-longer-verify-byzantine-plan-commitment-under-partial-evidence-decay.warrant.json
# Markdown SHA-256:   cdbf637bcc9c5903915148ec1d0c15379d91df8525c28db873b8429aae6c357c
# Code AST SHA-256:   9882a015abe1562a3827f438b5ea226a5d86e54424139d717932e516dfb07f1e
# Verified Classes:   DanglingCommitmentError, Certificate, CommitmentRecord, Agent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingCommitmentError(RuntimeError):
    """Raised when an agent attempts to act on a commitment whose
    signer-identified certificate is no longer retrievable."""


@dataclass
class Certificate:
    plan_hash: str
    view: int
    signers: frozenset  # signer identities, NOT a digest
    votes: dict = field(default_factory=dict)  # signer -> signed vote

    def intersects(self, other: "Certificate", f: int) -> bool:
        return len(self.signers & other.signers) >= f + 1


@dataclass
class CommitmentRecord:
    plan_hash: str
    view: int
    certificate_handle: Optional[str]  # None => digest-only, unsafe
    flag: str = "COMMITTED"


class Agent:
    def __init__(self, agent_id: str, f: int, store: dict):
        self.agent_id = agent_id
        self.f = f
        self.store = store  # replicated certificate store

    def resolve_certificate(self, rec: CommitmentRecord) -> Certificate:
        if rec.certificate_handle is None:
            raise DanglingCommitmentError(
                f"{self.agent_id}: commitment to {rec.plan_hash}@v{rec.view} "
                f"holds only a digest; signer set unrecoverable"
            )
        cert = self.store.get(rec.certificate_handle)
        if cert is None or not cert.signers:
            raise DanglingCommitmentError(
                f"{self.agent_id}: certificate handle "
                f"{rec.certificate_handle} did not dereference to a signer set"
            )
        return cert

    def act_on_commitment(self, rec: CommitmentRecord,
                          rival: Optional[Certificate] = None) -> str:
        # Fail closed: cannot act without a verifiable certificate.
        cert = self.resolve_certificate(rec)

        if rival is not None:
            if not cert.intersects(rival, self.f):
                raise DanglingCommitmentError(
                    f"{self.agent_id}: cert for {rec.plan_hash} does not "
                    f"intersect rival signer set; safety proof unavailable"
                )
        return f"EXECUTE {rec.plan_hash}@v{rec.view}"


def commit_plan(agent: Agent, plan_hash: str, view: int,
                signers: frozenset, votes: dict) -> CommitmentRecord:
    n, f = 6, agent.f
    if len(signers) < 2 * f + 1:
        raise DanglingCommitmentError(
            f"insufficient quorum: {len(signers)} < {2 * f + 1}"
        )
    cert = Certificate(plan_hash, view, signers, votes)
    handle = f"cert:{plan_hash}:{view}"
    # Durability invariant: certificate stored BEFORE flag is set.
    agent.store[handle] = cert
    return CommitmentRecord(plan_hash, view, certificate_handle=handle)
