# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegated-capability-from-silently-widening-its-own-contract-during-agent-to-agent-re-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegated-capability-from-silently-widening-its-own-contract-during-agent-to-agent-re-negotiation.warrant.json
# Markdown SHA-256:   a16bab7c7db989b0f4f2d4d31a2afcddf9858b17ebb6a5cd8dad8a5f891eccc2
# Code AST SHA-256:   edcd06c90cf9601b81f2b9b053bc087b848ad043807642f60271e3f818035845
# Verified Classes:   ContractWideningError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json


class ContractWideningError(RuntimeError):
    """Raised when a peer returns a capability descriptor that is a strict
    superset of the contract the orchestrator validated at handshake time."""


def descriptor_hash(descriptor: dict) -> str:
    canonical = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def is_strict_superset(accepted: dict, proposed: dict) -> bool:
    """True if `proposed` accepts strictly more than `accepted`.

    A field present in `proposed` but absent in `accepted` is a widening.
    A relaxed constraint (e.g. max_tokens 4096 -> unbounded) is a widening.
    A field with a default that injects output the caller did not budget for
    is a widening even though the field is 'optional'.
    """
    accepted_fields = accepted.get("fields", {})
    proposed_fields = proposed.get("fields", {})
    for name, spec in proposed_fields.items():
        if name not in accepted_fields:
            return True
        if spec.get("has_default") and not accepted_fields[name].get("has_default"):
            return True
        if spec.get("constraint") != accepted_fields[name].get("constraint"):
            return True
    return False


def verify_delegation_envelope(
    signed_hash: str,
    accepted_descriptor: dict,
    effective_descriptor: dict,
) -> None:
    if descriptor_hash(accepted_descriptor) != signed_hash:
        raise ContractWideningError(
            f"accepted descriptor hash {descriptor_hash(accepted_descriptor)[:12]} "
            f"does not match signed envelope {signed_hash[:12]}"
        )
    if is_strict_superset(accepted_descriptor, effective_descriptor):
        raise ContractWideningError(
            f"peer widened contract: accepted={descriptor_hash(accepted_descriptor)[:12]} "
            f"effective={descriptor_hash(effective_descriptor)[:12]}; "
            "re-acceptance round-trip required before proceeding"
        )
    # Narrowing or exact match is safe; proceed under the signed contract.
