# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-commitment-logs-when-a-consensus-quorum-forms-over-a-partially-observed-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-commitment-logs-when-a-consensus-quorum-forms-over-a-partially-observed-plan.warrant.json
# Markdown SHA-256:   dc59e2cdd4b9055774759f732902b146fe2b6611620ebb4632b22ee3a8aef97a
# Code AST SHA-256:   168df7a3340af9c250ed38695e635bb97bfdd64519f45b1988864d06538f8824
# Verified Classes:   UnsoundQuorumError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class UnsoundQuorumError(RuntimeError):
    """Raised when a consensus quorum authorizes a plan step that no voting
    agent observed or validly delegated. Quorum is arithmetically valid
    but epistemically unsound; plan must not execute."""
    pass


def verify_quorum_provenance(plan, commitment_logs, quorum_votes):
    """
    plan: dict step_id -> {'preconditions': set[str], ...}
    commitment_logs: dict agent_id -> list of entries, each:
        {'step_id', 'observed': bool, 'delegated_to': agent_id|None,
         'hash', 'prev_hash', 'signature'}
    quorum_votes: dict agent_id -> set[step_id]  (steps this agent voted to authorize)

    Returns None if sound. Raises UnsoundQuorumError otherwise.
    """
    # Step 1: validate hash chains and signatures (necessary, not sufficient).
    for agent_id, entries in commitment_logs.items():
        prev = None
        for entry in entries:
            if entry['prev_hash'] != prev:
                raise UnsoundQuorumError(
                    f"chain break in log for {agent_id} at step {entry['step_id']}"
                )
            prev = entry['hash']

    # Step 2: build observation index from logs.
    observed = {}      # (agent_id, step_id) -> bool
    delegated = {}     # (agent_id, step_id) -> agent_id | None
    for agent_id, entries in commitment_logs.items():
        for entry in entries:
            observed[(agent_id, entry['step_id'])] = entry['observed']
            delegated[(agent_id, entry['step_id'])] = entry.get('delegated_to')

    # Step 3: for every vote, trace to an observation or a valid delegation chain.
    for agent_id, voted_steps in quorum_votes.items():
        for step_id in voted_steps:
            if step_id not in plan:
                raise UnsoundQuorumError(
                    f"agent {agent_id} voted on unknown step {step_id}"
                )
            if observed.get((agent_id, step_id), False):
                continue  # directly observed; sound
            target = delegated.get((agent_id, step_id))
            if target is None:
                raise UnsoundQuorumError(
                    f"agent {agent_id} voted to authorize step {step_id} "
                    f"without observing its preconditions and without delegation"
                )
            # Follow delegation chain; must terminate at a true observation.
            seen = {agent_id}
            cursor = target
            while cursor is not None:
                if cursor in seen:
                    raise UnsoundQuorumError(
                        f"delegation cycle for step {step_id}: {seen}"
                    )
                seen.add(cursor)
                if observed.get((cursor, step_id), False):
                    break
                cursor = delegated.get((cursor, step_id))
            else:
                raise UnsoundQuorumError(
                    f"delegation chain for step {step_id} from {agent_id} "
                    f"terminates without a true observation"
                )
    return None
