# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-divergent-audit-trails-before-a-federated-capability-grant-is-honored.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-divergent-audit-trails-before-a-federated-capability-grant-is-honored.warrant.json
# Markdown SHA-256:   b0badc10abaabaf505984c8286a8b6fc05e22b9120aa24872d26bd010ff73dbd
# Code AST SHA-256:   87c51caa8aad8f362e73df0a11eaa20bde2311e9eddb0d2241a03a8ff9378a72
# Verified Classes:   AuditTrailDivergenceError, Warrant, ProviderState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class AuditTrailDivergenceError(RuntimeError):
    """Raised when a capability warrant's trail digest cannot be proven to
    descend from the provider's last-reconciled root, despite matching
    policy_version. Indicates concurrent policy divergence, not staleness."""


@dataclass
class Warrant:
    consumer_org: str
    policy_version: int
    trail_digest: str            # Merkle root of consumer's audit log
    last_reconciled_root: str    # consumer's view of last common ancestor
    ancestry_proof: list[str]    # sibling hashes from last_reconciled_root -> trail_digest


@dataclass
class ProviderState:
    org: str
    policy_version: int
    reconciled_root: str         # provider's last-reconciled common ancestor
    log_root: str                # provider's current audit log root


def _merkle_parent(left: str, right: str) -> str:
    return hashlib.sha256((left + right).encode()).hexdigest()


def _verify_ancestry(proof: list[str], start: str, end: str) -> bool:
    """Fold the ancestry proof from the claimed common ancestor to the
    consumer's current root. Returns True iff the fold reproduces `end`."""
    node = start
    for sibling in proof:
        node = _merkle_parent(node, sibling)
    return node == end


def honor_capability(warrant: Warrant, state: ProviderState) -> bool:
    # Version equality is necessary but NOT sufficient.
    if warrant.policy_version != state.policy_version:
        raise AuditTrailDivergenceError(
            f"version mismatch: warrant={warrant.policy_version} "
            f"provider={state.policy_version}"
        )

    # The gate: the consumer's trail must provably descend from the
    # provider's last-reconciled root. Version match alone is rejected.
    if warrant.last_reconciled_root != state.reconciled_root:
        raise AuditTrailDivergenceError(
            f"no common ancestor: consumer_reconciled={warrant.last_reconciled_root} "
            f"provider_reconciled={state.reconciled_root}; "
            f"reconcile before requesting cap"
        )

    if not _verify_ancestry(
        warrant.ancestry_proof,
        warrant.last_reconciled_root,
        warrant.trail_digest,
    ):
        raise AuditTrailDivergenceError(
            f"ancestry proof does not fold to trail_digest "
            f"{warrant.trail_digest}; consumer log diverged from reconciled root"
        )

    # Only now is the grant semantically sound.
    return True
