# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-anchor-substitution-during-cross-org-policy-negotiation-in-federated-agent-meshes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-anchor-substitution-during-cross-org-policy-negotiation-in-federated-agent-meshes.warrant.json
# Markdown SHA-256:   ab91335c9d1b040047935a1ef00fb792d0cb2c3f2f338b90273506ed39c1844e
# Code AST SHA-256:   e8672b1b17bc40cdcba93b8bb0aee72d1e4cd0a962aef1a98a55de39e37c22e6
# Verified Classes:   TrustAnchorSubstitutionError, TrustAnchor, Negotiation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TrustAnchorSubstitutionError(RuntimeError):
    """Raised when a warrant is validated against an anchor version
    other than the one pinned at negotiation start."""
    pass


@dataclass(frozen=True)
class TrustAnchor:
    anchor_version: int
    signing_keys: frozenset[str]
    manifest: dict  # e.g. {"attestation": "hardware", "data_residency": "eu"}

    def manifest_digest(self) -> str:
        canon = repr(sorted(self.manifest.items())).encode()
        return hashlib.sha256(canon).hexdigest()


@dataclass
class Negotiation:
    pinned: TrustAnchor
    accepted_warrants: list = field(default_factory=list)


def classify_delta(old: TrustAnchor, new: TrustAnchor) -> str:
    """Return 'identical', 'additive', or 'restrictive'."""
    if old.manifest_digest() == new.manifest_digest():
        return "identical"
    old_keys = old.manifest.keys()
    new_keys = new.manifest.keys()
    # Restrictive: removes a key, changes a value, or adds a required clause.
    for k in old_keys:
        if k not in new.manifest or new.manifest[k] != old.manifest[k]:
            return "restrictive"
    for k in new_keys:
        if k not in old.manifest:
            return "restrictive"  # new required clause introduced mid-flight
    return "additive"


def validate_warrant(
    negotiation: Negotiation,
    warrant: dict,
    current_anchor: TrustAnchor,
    revoked_keys: frozenset[str],
) -> None:
    """Validate a warrant against the negotiation's pinned anchor version."""
    ref_version = warrant.get("anchor_version_ref")
    if ref_version is None:
        raise TrustAnchorSubstitutionError(
            "warrant lacks anchor_version_ref; cannot bind to negotiation"
        )
    if ref_version != negotiation.pinned.anchor_version:
        raise TrustAnchorSubstitutionError(
            f"warrant references anchor v{ref_version}, "
            f"negotiation pinned v{negotiation.pinned.anchor_version}"
        )

    signer = warrant.get("signer_key")
    if signer in revoked_keys:
        raise TrustAnchorSubstitutionError(
            f"warrant signed by revoked key {signer!r}"
        )
    if signer not in negotiation.pinned.signing_keys:
        # A key from a newer anchor is not acceptable mid-negotiation.
        raise TrustAnchorSubstitutionError(
            f"signer {signer!r} not in pinned key set "
            f"v{negotiation.pinned.anchor_version}"
        )

    # If the peer has rotated, classify the delta before proceeding.
    if current_anchor.anchor_version != negotiation.pinned.anchor_version:
        delta = classify_delta(negotiation.pinned, current_anchor)
        if delta == "restrictive":
            raise TrustAnchorSubstitutionError(
                f"trust anchor rotated mid-negotiation: "
                f"v{negotiation.pinned.anchor_version} -> "
                f"v{current_anchor.anchor_version} with restrictive delta; "
                f"fail closed and re-negotiate"
            )
        # 'identical' or 'additive': continue under pinned version.
    negotiation.accepted_warrants.append(warrant)
