# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-byzantine-quorum-over-agent-proposed-facts-when-the-adversary-controls-the-attestation-channel-rather-than-the-agents-t.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-byzantine-quorum-over-agent-proposed-facts-when-the-adversary-controls-the-attestation-channel-rather-than-the-agents-t.warrant.json
# Markdown SHA-256:   fe7709595e9b6d9d1abe6e96a50f569372330722132828d73664071912bfea19
# Code AST SHA-256:   2440810d35f2de6d605b51e706d278f7ab879219ce8592da6cc0ea081d11ddcf
# Verified Classes:   QuorumCoObservationError, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class QuorumCoObservationError(RuntimeError):
    """Raised when a 2f+1 attestation set cannot be proven co-observed by all signers."""


@dataclass(frozen=True)
class Attestation:
    signer: str
    fact_id: str
    verdict: str
    view: int
    prev_head: Optional[str]      # hash of the log head this signer observed
    envelope_hash: str            # hash over (signer, fact_id, verdict, view, prev_head)


def _h(*parts: str) -> str:
    return hashlib.sha256("|".join(parts).encode()).hexdigest()


def verify_co_observed_quorum(
    fact_id: str,
    view: int,
    attestations: list[Attestation],
    f: int,
) -> str:
    """
    Commit a fact only if a 2f+1 quorum is provably co-observed:
    every attestation must chain back to the SAME log head for (fact_id, view).
    Returns the committed verdict.
    """
    quorum = 2 * f + 1
    if len(attestations) < quorum:
        raise QuorumCoObservationError(
            f"insufficient attestations for {fact_id}@{view}: "
            f"have {len(attestations)}, need {quorum}"
        )

    heads = {a.prev_head for a in attestations}
    if len(heads) != 1 or None in heads:
        # Multiple distinct log heads (or a missing chain link) => channel equivocation
        # or a laundered nonce. Signatures may all be valid; co-observation is not.
        raise QuorumCoObservationError(
            f"attestations for {fact_id}@{view} are not co-observed: "
            f"{len(heads)} distinct log heads {sorted(map(str, heads))}"
        )

    verdicts = {a.verdict for a in attestations}
    if len(verdicts) != 1:
        raise QuorumCoObservationError(
            f"conflicting verdicts within single co-observed view: {verdicts}"
        )

    # Recompute envelope integrity end-to-end (no gaps in the per-fact chain).
    for a in attestations:
        expected = _h(a.signer, a.fact_id, a.verdict, str(a.view), a.prev_head or "")
        if a.envelope_hash != expected:
            raise QuorumCoObservationError(
                f"envelope hash mismatch for signer {a.signer} on {fact_id}@{view}"
            )

    return verdicts.pop()


def commit_fact_or_escalate(fact_id: str, view: int, attestations: list[Attestation], f: int) -> str:
    try:
        return verify_co_observed_quorum(fact_id, view, attestations, f)
    except QuorumCoObservationError:
        # Do NOT write a forked belief into semantic memory; escalate to view-change.
        raise
