# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-claim-divergence-during-dynamic-delegation-routing-in-multi-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-claim-divergence-during-dynamic-delegation-routing-in-multi-agent-swarms.warrant.json
# Markdown SHA-256:   646a07947c93acbb299a2b01b42ba64b915e59fe0389b741657d219373e38a94
# Code AST SHA-256:   14227bde0369013ea7494ef7cb3a517ccdf8f342690a42342f52079dfd53ebbe
# Verified Classes:   CapabilityClaimDivergence, Invocation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class CapabilityClaimDivergence(RuntimeError):
    """Raised when a delegate returns a success envelope whose output does not
    validate against the router-held schema for the dispatched input."""
    pass


@dataclass
class Invocation:
    delegate_id: str
    skill: str
    input_payload: dict
    expected_output_schema: dict  # held by the router, never by the delegate


def route_and_validate(inv: Invocation, delegate_response: dict,
                       divergence_counts: dict[tuple[str, str], int]) -> dict:
    # Hard failure first: liveness, not correctness.
    if delegate_response.get("status") != "ok":
        raise ConnectionError(f"hard failure from {inv.delegate_id}: "
                              f"{delegate_response.get('status')}")

    # Divergence signal 1: delegate echoed a schema different from ours.
    echoed = delegate_response.get("applied_schema")
    if echoed is not None and echoed != inv.expected_output_schema:
        _record(divergence_counts, inv)
        raise CapabilityClaimDivergence(
            f"{inv.delegate_id}/{inv.skill} echoed a schema that differs from "
            f"the router-held schema; delegate self-reported a transformed domain"
        )

    # Divergence signal 2: provenance names a fallback path.
    provenance = delegate_response.get("provenance", "")
    if "fallback" in provenance or "truncat" in provenance:
        _record(divergence_counts, inv)
        raise CapabilityClaimDivergence(
            f"{inv.delegate_id}/{inv.skill} answered via fallback path "
            f"'{provenance}'; manifest did not declare this path"
        )

    # Divergence signal 3: output does not validate against router schema.
    output = delegate_response.get("output", {})
    missing = set(inv.expected_output_schema.get("required", [])) - set(output)
    if missing:
        _record(divergence_counts, inv)
        raise CapabilityClaimDivergence(
            f"{inv.delegate_id}/{inv.skill} output missing required fields "
            f"{sorted(missing)}; schema was likely truncated inside the delegate"
        )

    return output


def _record(counts: dict[tuple[str, str], int], inv: Invocation) -> None:
    key = (inv.delegate_id, inv.skill)
    counts[key] = counts.get(key, 0) + 1
    if counts[key] >= 2:
        # Second divergence: evict from candidate pool for this skill.
        raise CapabilityClaimDivergence(
            f"{inv.delegate_id}/{inv.skill} exceeded divergence budget "
            f"({counts[key]}); evicting from pool and re-routing"
        )
