# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-quorum-certificate-as-non-transferable-across-task-epochs-and-why-does-re-signing-a-prior-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-quorum-certificate-as-non-transferable-across-task-epochs-and-why-does-re-signing-a-prior-commit.warrant.json
# Markdown SHA-256:   3a64b82a03af126e7722b50e9ba96b6e77057cfc854a0e9c9928dc5344a1e85a
# Code AST SHA-256:   fa0ec51cd11acd5b817442cebbecef6c4e2699678731ad70bcd3e00a93f13347
# Verified Classes:   StaleQuorumCertificateError, Membership, QuorumCertificate
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleQuorumCertificateError(RuntimeError):
    """Raised when a QC is presented for commit under a membership it no longer satisfies."""
    pass


@dataclass(frozen=True)
class Membership:
    epoch: int
    weights: dict            # agent_id -> int weight
    revoked: frozenset       # agents revoked for equivocation as of this epoch

    def quorum_threshold(self) -> int:
        total = sum(self.weights.values())
        f = (total - 1) // 3
        return 2 * f + 1

    def membership_digest(self) -> str:
        payload = repr(sorted(self.weights.items())) + repr(sorted(self.revoked))
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class QuorumCertificate:
    task_id: str
    state_digest: str
    epoch: int
    signers: frozenset
    provenance: frozenset    # transitive ancestry of signers, incl. prior-epoch signers
    membership_digest: str


def verify_commit_proof(qc: QuorumCertificate, current: Membership) -> bool:
    # 1. Membership binding: the QC must be scoped to the CURRENT membership.
    if qc.membership_digest != current.membership_digest():
        raise StaleQuorumCertificateError(
            f"QC epoch {qc.epoch} bound to membership {qc.membership_digest[:8]}, "
            f"current is {current.membership_digest()[:8]}"
        )

    # 2. Revocation in ancestry: no revoked agent may appear in provenance.
    tainted = qc.provenance & current.revoked
    if tainted:
        raise StaleQuorumCertificateError(
            f"QC provenance touches revoked agents {sorted(tainted)}"
        )

    # 3. Signers must be a legal subset of current membership.
    illegal = qc.signers - set(current.weights)
    if illegal:
        raise StaleQuorumCertificateError(
            f"QC signers {sorted(illegal)} not in current membership"
        )

    # 4. Threshold under CURRENT weights, not embedded-epoch weights.
    weight = sum(current.weights[a] for a in qc.signers)
    if weight < current.quorum_threshold():
        raise StaleQuorumCertificateError(
            f"QC weight {weight} below current threshold {current.quorum_threshold()}"
        )
    return True


def re_propose_cross_epoch(
    old_qc: QuorumCertificate, current: Membership, fresh_signers: frozenset
) -> QuorumCertificate:
    """Correct path: re-propose, gathering FRESH signatures under current membership."""
    if old_qc.state_digest is None:
        raise StaleQuorumCertificateError("empty state digest")
    # The old QC is a proposal seed only; it cannot satisfy threshold itself.
    if not (fresh_signers <= set(current.weights)):
        raise StaleQuorumCertificateError("fresh signers not in current membership")
    weight = sum(current.weights[a] for a in fresh_signers)
    if weight < current.quorum_threshold():
        raise StaleQuorumCertificateError(
            f"fresh quorum weight {weight} < {current.quorum_threshold()}"
        )
    return QuorumCertificate(
        task_id=old_qc.task_id,
        state_digest=old_qc.state_digest,
        epoch=current.epoch,
        signers=fresh_signers,
        provenance=fresh_signers,          # ancestry RESET: no laundering
        membership_digest=current.membership_digest(),
    )
