# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-certificate-forgery-from-collapsing-byzantine-task-allocation-when-agent-signatures-attest-liveness-but-not-intent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-certificate-forgery-from-collapsing-byzantine-task-allocation-when-agent-signatures-attest-liveness-but-not-intent.warrant.json
# Markdown SHA-256:   425ce305ffbc4b2971aa05fed702c0877d2b32e3b7a3adedc72769d53291ca1a
# Code AST SHA-256:   949c935e993e864e79f77f059b37626f899d4d1fbfae552e4f2bab8b2a759e23
# Verified Classes:   QCForgeryError, Allocation, Proposal
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class QCForgeryError(RuntimeError):
    """Raised when two quorum certificates certify distinct hashes for equal
    semantic allocations, proving the signed payload was not canonicalized."""
    pass


@dataclass(frozen=True)
class Allocation:
    task_id: str
    assignee: str


@dataclass
class Proposal:
    view: int
    task_id: str
    payload: dict[str, Any]  # may carry non-semantic fields (nonce, order)


def semantic_projection(payload: dict[str, Any]) -> tuple[tuple[str, str], ...]:
    """The canonical semantic state: sorted (task, assignee) pairs only.
    Strips nonce, timestamps, insertion order — anything not part of intent."""
    allocs = payload.get("allocations", [])
    return tuple(sorted((a["task_id"], a["assignee"]) for a in allocs))


def unsafe_hash(proposal: Proposal) -> str:
    """Hashes raw serialization — vulnerable to nonce/order variation."""
    raw = repr(sorted(proposal.payload.items())) + repr(proposal.payload.get("nonce"))
    return hashlib.sha256(raw.encode()).hexdigest()


def safe_hash(proposal: Proposal) -> str:
    """Hashes canonical semantic projection — bijective onto semantic states."""
    canon = repr(semantic_projection(proposal.payload))
    return hashlib.sha256(canon.encode()).hexdigest()


def verify_qc_pair(qc_a: dict, qc_b: dict, hash_fn) -> None:
    """Enforce the invariant: distinct QC hashes must imply distinct semantics.
    If two QCs share semantic content but differ in hash, the schema is unsound."""
    sem_a = qc_a["semantic"]
    sem_b = qc_b["semantic"]
    hash_a = qc_a["hash"]
    hash_b = qc_b["hash"]

    if sem_a == sem_b and hash_a != hash_b:
        raise QCForgeryError(
            f"QC forgery: identical semantics {sem_a} certified under two hashes "
            f"{hash_a[:12]}.. and {hash_b[:12]}..; payload not canonicalized. "
            f"Honest agents can be induced to sign both, breaking 2f+1 intersection."
        )


def run_audit() -> None:
    p1 = Proposal(view=7, task_id="T1",
                  payload={"allocations": [{"task_id": "T1", "assignee": "A"},
                                            {"task_id": "T2", "assignee": "B"}],
                           "nonce": 111})
    p2 = Proposal(view=7, task_id="T1",
                  payload={"allocations": [{"task_id": "T2", "assignee": "B"},
                                            {"task_id": "T1", "assignee": "A"}],
                           "nonce": 999})

    qc_unsafe_a = {"semantic": semantic_projection(p1.payload), "hash": unsafe_hash(p1)}
    qc_unsafe_b = {"semantic": semantic_projection(p2.payload), "hash": unsafe_hash(p2)}

    # Unsafe schema: equal semantics, different hashes -> forgery detected.
    verify_qc_pair(qc_unsafe_a, qc_unsafe_b, unsafe_hash)

    # Safe schema would collapse both to one hash; this line is unreachable
    # under the unsafe schema above, proving the guardrail fires.
    qc_safe_a = {"semantic": semantic_projection(p1.payload), "hash": safe_hash(p1)}
    qc_safe_b = {"semantic": semantic_projection(p2.payload), "hash": safe_hash(p2)}
    verify_qc_pair(qc_safe_a, qc_safe_b, safe_hash)  # no raise: canonicalized


if __name__ == "__main__":
    run_audit()
