# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-manifest-divergence-during-cross-org-agent-federation-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-manifest-divergence-during-cross-org-agent-federation-handshake.warrant.json
# Markdown SHA-256:   f86552b2e965519f3a8620178faeb048c07ea8baa70bbd65439785868f5cf9ba
# Code AST SHA-256:   07749baa94e358b1bb86a2e0639590421d14fc9e86bd49421c5bcdbe4207d65c
# Verified Classes:   CapabilityDivergenceError, EffectiveContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityDivergenceError(RuntimeError):
    """Raised when cached and live effective contracts disagree across a federation boundary."""
    pass


@dataclass(frozen=True)
class EffectiveContract:
    capability_id: str
    provider_org: str
    constraints: dict[str, Any]
    hard_flags: dict[str, bool]

    def canonical(self) -> str:
        return json.dumps(
            {
                "capability_id": self.capability_id,
                "provider_org": self.provider_org,
                "constraints": dict(sorted(self.constraints.items())),
                "hard_flags": dict(sorted(self.hard_flags.items())),
            },
            sort_keys=True,
            separators=(",", ":"),
        )

    def digest(self) -> str:
        return hashlib.sha256(self.canonical().encode()).hexdigest()


def materialize(manifest: dict[str, Any], defaults: dict[str, Any]) -> EffectiveContract:
    """Resolve omitted fields against provider defaults so presence/absence is erased."""
    constraints = dict(defaults)
    constraints.update(manifest.get("constraints", {}))
    hard_flags = {k: bool(v) for k, v in manifest.get("hard_flags", {}).items()}
    for key in constraints:
        hard_flags.setdefault(key, False)
    return EffectiveContract(
        capability_id=manifest["capability_id"],
        provider_org=manifest["provider_org"],
        constraints=constraints,
        hard_flags=hard_flags,
    )


def negotiate(
    cached_manifest: dict[str, Any],
    live_manifest: dict[str, Any],
    provider_defaults: dict[str, Any],
) -> EffectiveContract:
    cached = materialize(cached_manifest, provider_defaults)
    live = materialize(live_manifest, provider_defaults)

    if cached.capability_id != live.capability_id:
        raise CapabilityDivergenceError(
            f"capability_id mismatch: cached={cached.capability_id} live={live.capability_id}"
        )
    if cached.provider_org != live.provider_org:
        raise CapabilityDivergenceError(
            f"provider_org mismatch: cached={cached.provider_org} live={live.provider_org}"
        )

    if cached.digest() != live.digest():
        diverging = {
            k: (cached.constraints.get(k), live.constraints.get(k))
            for k in set(cached.constraints) | set(live.constraints)
            if cached.constraints.get(k) != live.constraints.get(k)
            or cached.hard_flags.get(k) != live.hard_flags.get(k)
        }
        raise CapabilityDivergenceError(
            f"effective contract diverged for {cached.provider_org}/{cached.capability_id}: "
            f"{diverging}. Refusing handshake; warrants minted against cached contract "
            f"({cached.digest()[:12]}) are suspect."
        )

    return live


def cache_key(contract: EffectiveContract) -> tuple[str, str, str]:
    """Identity includes provider_org and content digest; version triple alone is insufficient."""
    return (contract.provider_org, contract.capability_id, contract.digest())
