# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-capability-negotiation-has-silently-collapsed-to-the-intersection-set-rather-than-the-union-set.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-capability-negotiation-has-silently-collapsed-to-the-intersection-set-rather-than-the-union-set.warrant.json
# Markdown SHA-256:   b310dd86118f44454db699589b68b03a3bb4d4aa9f3ee2bafc6c7fb3e054bc23
# Code AST SHA-256:   f3a67d800f11a9ae69c827a86a2b1199759a9205fa85ad5a14e5a4db7adf12ff
# Verified Classes:   CapabilityCollapseError, Capability
# Defensive Guards:   11 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class CapabilityCollapseError(RuntimeError):
    """Raised when a negotiated capability set has silently collapsed below
    the delegator's planned projection (schema, scope, or claim divergence)."""
    pass


@dataclass
class Capability:
    name: str
    schema: str
    scopes: Set[str] = field(default_factory=set)
    claims: Dict[str, str] = field(default_factory=dict)


def negotiate_and_attest(
    planned: Dict[str, Capability],
    peer_manifest: Dict[str, Capability],
    peer_echo: Dict[str, Capability],
    strict: bool = True,
) -> Dict[str, Capability]:
    """Compute the effective capability set and attest it against the plan.

    Under strict mode, any schema-version mismatch, absent required scope, or
    unrecognized claim raises CapabilityCollapseError before any mutating call.
    Under permissive mode, the collapse is computed and returned with a warning
    annotation, but the caller is responsible for treating it as unsafe.
    """
    effective: Dict[str, Capability] = {}

    for name, want in planned.items():
        have = peer_manifest.get(name)
        if have is None:
            if strict:
                raise CapabilityCollapseError(
                    f"capability {name!r} absent from peer manifest"
                )
            continue

        # Axis 1: schema strictness. Name match with version drift binds low.
        if have.schema != want.schema:
            if strict:
                raise CapabilityCollapseError(
                    f"schema drift on {name!r}: want {want.schema}, "
                    f"peer offers {have.schema} (lossy bind)"
                )
            bound_schema = min(want.schema, have.schema)
        else:
            bound_schema = want.schema

        # Axis 2: scope totality. Absent scope is denial, not consent.
        granted_scopes = want.scopes & have.scopes
        missing = want.scopes - have.scopes
        if missing and strict:
            raise CapabilityCollapseError(
                f"scope collapse on {name!r}: required {sorted(missing)} "
                f"absent from peer manifest (absence != consent)"
            )

        # Axis 3: claim closure. Unrecognized claims must reject, not drop.
        bound_claims: Dict[str, str] = {}
        for k, v in want.claims.items():
            if k not in have.claims:
                if strict:
                    raise CapabilityCollapseError(
                        f"claim closure violation on {name!r}: "
                        f"claim {k!r}={v!r} unrecognized by peer"
                    )
                continue
            if have.claims[k] != v:
                if strict:
                    raise CapabilityCollapseError(
                        f"claim conflict on {name!r}: {k!r} "
                        f"want {v!r}, peer {have.claims[k]!r}"
                    )
                continue
            bound_claims[k] = v

        effective[name] = Capability(
            name=name,
            schema=bound_schema,
            scopes=granted_scopes,
            claims=bound_claims,
        )

    # Attestation: peer echo must match the effective set exactly.
    for name, eff in effective.items():
        echo = peer_echo.get(name)
        if echo is None:
            raise CapabilityCollapseError(
                f"attestation gap: peer did not echo capability {name!r}"
            )
        if echo.schema != eff.schema:
            raise CapabilityCollapseError(
                f"attestation schema mismatch on {name!r}: "
                f"effective {eff.schema}, echo {echo.schema}"
            )
        if echo.scopes != eff.scopes:
            raise CapabilityCollapseError(
                f"attestation scope mismatch on {name!r}: "
                f"effective {sorted(eff.scopes)}, echo {sorted(echo.scopes)}"
            )
        if echo.claims != eff.claims:
            raise CapabilityCollapseError(
                f"attestation claim mismatch on {name!r}: "
                f"effective {eff.claims}, echo {echo.claims}"
            )

    return effective


def preflight_federation(
    planned: Dict[str, Capability],
    peer_manifest: Dict[str, Capability],
    peer_echo: Dict[str, Capability],
) -> Dict[str, Capability]:
    """Run strict negotiation + attestation before any mutating tool call.

    Callers MUST invoke this and MUST NOT proceed to mutating calls if it
    raises. A successful return is the only structural signal that the
    negotiated set equals the planned projection.
    """
    try:
        return negotiate_and_attest(planned, peer_manifest, peer_echo, strict=True)
    except CapabilityCollapseError:
        raise
    except Exception as exc:  # noqa: BLE001 - surface unexpected negotiation faults
        raise CapabilityCollapseError(
            f"unexpected negotiation fault: {type(exc).__name__}: {exc}"
        ) from exc
