# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-verifier-gated-speculative-planning-is-about-to-commit-on-a-stale-consensus-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-verifier-gated-speculative-planning-is-about-to-commit-on-a-stale-consensus-quorum.warrant.json
# Markdown SHA-256:   4e083678cb87316b21b29d34313b7b51f0c8bf638aab4241c418a059b43015fb
# Code AST SHA-256:   d33d1731c921e2b04355e0f7431ce4b3cc98db701f2c647f0b87c0cfc56ed1b8
# Verified Classes:   AttestationSkewError, Attestation, PlanBranch, Quorum
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AttestationSkewError(RuntimeError):
    """Raised when quorum attestations reference a plan digest that no longer
    matches the committed/executed plan digest at finalization time."""
    pass


@dataclass
class Attestation:
    auditor_id: str
    task_id: str
    plan_digest: str
    verdict_digest: str


@dataclass
class PlanBranch:
    task_id: str
    steps: list
    superseded: bool = False

    def digest(self) -> str:
        payload = f"{self.task_id}|{'|'.join(self.steps)}".encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class Quorum:
    threshold: int
    attestations: list = field(default_factory=list)

    def count_for(self, plan_digest: str) -> int:
        return sum(1 for a in self.attestations if a.plan_digest == plan_digest)


def verifier_repair(branch: PlanBranch, bad_step: str, replacement: str) -> PlanBranch:
    """Verifier supersedes a branch; returns a NEW branch with a NEW digest."""
    if bad_step not in branch.steps:
        raise AttestationSkewError(f"repair target {bad_step!r} not in branch")
    new_steps = [replacement if s == bad_step else s for s in branch.steps]
    branch.superseded = True
    return PlanBranch(task_id=branch.task_id, steps=new_steps)


def finalize_task(committed: PlanBranch, quorum: Quorum) -> str:
    """Close the task only if the quorum's attestations cover the committed digest."""
    committed_digest = committed.digest()
    votes = quorum.count_for(committed_digest)

    # The invariant: attestations over any other digest do not count.
    if votes < quorum.threshold:
        stale = {a.plan_digest for a in quorum.attestations} - {committed_digest}
        raise AttestationSkewError(
            f"task {committed.task_id}: committed digest {committed_digest[:12]} "
            f"has {votes}/{quorum.threshold} valid attestations; "
            f"stale digests present: {[d[:12] for d in stale]}"
        )
    return committed_digest


# --- Failure trace reproducing the observed skew ---
branch = PlanBranch(task_id="4471", steps=["retrieve", "call:search_v1", "synthesize"])
d0 = branch.digest()

quorum = Quorum(threshold=4)
# Three auditors sign the pre-repair proposal.
for i in range(3):
    quorum.attestations.append(Attestation(f"aud-{i}", "4471", d0, "verdict-0"))

# Verifier repairs the branch; digest changes to d1.
repaired = verifier_repair(branch, "call:search_v1", "call:search_v2")
d1 = repaired.digest()
assert d0 != d1

# Two late auditors sign the *stale* proposal record still carrying d0.
for i in range(3, 5):
    quorum.attestations.append(Attestation(f"aud-{i}", "4471", d0, "verdict-0"))

# Naive finalization would pass (5 >= 4). Guarded finalization fails closed.
try:
    finalize_task(repaired, quorum)
except AttestationSkewError as e:
    print(f"BLOCKED: {e}")
    # Correct remediation: re-propose d1 and require fresh attestations.
