# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-the-granted-but-unreachable-divergence-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-the-granted-but-unreachable-divergence-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   672414330e015a8288671c2c9720190676843c757bd916c08d5b19102eef2fd0
# Code AST SHA-256:   4e99f70df3da81086f269190487eae1f48d0f675cdfc3260c91f02c60fbc6b7b
# Verified Classes:   FederationBoundaryError, CapabilityContract, MaterializedPayload
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FederationBoundaryError(RuntimeError):
    """Raised when a federated capability call cannot be proven within policy."""


@dataclass
class CapabilityContract:
    capability_id: str
    fields: dict            # field name -> {"type": str, "policy_tag": Optional[str], "pii_safe": bool}
    tagger_version: str
    negotiated_at: float


@dataclass
class MaterializedPayload:
    capability_id: str
    arguments: dict         # field name -> value
    fired_tags: dict        # field name -> set of policy tags that fired at serialization


def enforce_federated_boundary(
    contract: CapabilityContract,
    payload: MaterializedPayload,
    current_tagger_version: str,
    max_contract_age_s: float = 3600.0,
    now: Optional[float] = None,
) -> None:
    import time
    now = time.time() if now is None else now

    if payload.capability_id != contract.capability_id:
        raise FederationBoundaryError(
            f"payload capability {payload.capability_id!r} does not match "
            f"contract {contract.capability_id!r}"
        )

    # Tag-set skew: contract was negotiated against a stale tagger.
    if contract.tagger_version != current_tagger_version:
        raise FederationBoundaryError(
            f"contract {contract.capability_id!r} negotiated under tagger "
            f"{contract.tagger_version!r} but current tagger is "
            f"{current_tagger_version!r}; re-negotiate before egress"
        )

    # Schema drift / contract staleness.
    if now - contract.negotiated_at > max_contract_age_s:
        raise FederationBoundaryError(
            f"contract {contract.capability_id!r} is stale "
            f"({now - contract.negotiated_at:.0f}s > {max_contract_age_s:.0f}s); "
            f"re-negotiate before egress"
        )

    # Core soundness check: every fired tag must be anchored in a declared,
    # policy-bound field, and that field's declared policy must cover the tag.
    for field_name, tags in payload.fired_tags.items():
        if not tags:
            continue
        declared = contract.fields.get(field_name)
        if declared is None:
            raise FederationBoundaryError(
                f"unanchored policy tag on field {field_name!r}: tags {sorted(tags)} "
                f"fired at serialization but field is not declared in contract "
                f"{contract.capability_id!r}"
            )
        declared_tag = declared.get("policy_tag")
        if declared_tag is None:
            raise FederationBoundaryError(
                f"unanchored policy tag on field {field_name!r}: tags {sorted(tags)} "
                f"fired but contract declares field with no policy_tag "
                f"(opaque-string smuggling path)"
            )
        if declared_tag not in tags and not declared.get("pii_safe", False):
            raise FederationBoundaryError(
                f"field {field_name!r} declared policy_tag {declared_tag!r} but "
                f"fired tags {sorted(tags)} are not covered and pii_safe is false; "
                f"capability-level guard is not a faithful proxy"
            )


# --- call site ---
def execute_federated_call(contract, payload, tagger_version):
    enforce_federated_boundary(contract, payload, tagger_version)
    # ... egress proceeds only after the soundness gate passes ...
    return {"status": "egressed", "capability": contract.capability_id}
