# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-cross-org-capability-attestation-that-is-valid-but-semantically-stale-at-the-policy-negotiation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-cross-org-capability-attestation-that-is-valid-but-semantically-stale-at-the-policy-negotiation-boundary.warrant.json
# Markdown SHA-256:   401b5ce1ca95b9c9a9e76506b538bba6281e90959609818c891102935c7fd020
# Code AST SHA-256:   ba4444081baee71b44e9c29bdf874a0cdfa6eef2e3aa38954014c49d82807e60
# Verified Classes:   StaleAttestationError, PolicyVersionMismatchError, MissingExecutionContextError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleAttestationError(RuntimeError):
    """Raised when a warrant's bound policy version does not match the
    callee's live execution policy at invocation time."""
    pass


class PolicyVersionMismatchError(StaleAttestationError):
    """Warrant names a policy version the callee can no longer execute."""
    pass


class MissingExecutionContextError(StaleAttestationError):
    """Callee returned a result without the mandatory execution_context
    block, meaning it executed outside the negotiated contract."""
    pass


def invoke_federated_tool(
    warrant: dict,
    callee_descriptor: dict,
    callee_invoke_fn,
) -> dict:
    """
    Invoke a cross-org tool under a warrant, enforcing that the callee
    executes pinned to the warrant's bound policy version.

    warrant: {
        "capability": str,
        "policy_version": str,      # e.g. "2026-06-17T14:00Z-7a3f"
        "expires_at": float,
        "signature": str,
    }
    callee_descriptor: {
        "capability": str,
        "live_policy_version": str,
        "executable_policy_versions": list[str],
    }
    """
    import time

    # 1. Signature + expiry checks are assumed done upstream (loud failures).
    if time.time() > warrant["expires_at"]:
        raise StaleAttestationError(
            f"warrant expired at {warrant['expires_at']}"
        )

    # 2. The critical check: can the callee still execute the bound version?
    bound = warrant["policy_version"]
    executable = callee_descriptor.get("executable_policy_versions", [])
    live = callee_descriptor.get("live_policy_version")

    if bound not in executable:
        # The callee has rolled its policy forward and no longer honors
        # the version this warrant was minted against. Fail closed;
        # do NOT let the callee fall forward to `live` silently.
        raise PolicyVersionMismatchError(
            f"warrant bound to policy_version={bound!r}, but callee "
            f"executes {executable!r} (live={live!r}). Re-negotiate."
        )

    if bound != live:
        # Bound version is still executable but is not the live policy.
        # This is legal (pinned execution) but must be surfaced to the
        # caller so it cannot mistake pinned-old for current.
        pinned_old = True
    else:
        pinned_old = False

    # 3. Invoke with an explicit pin. The callee must honor it.
    result = callee_invoke_fn(warrant=warrant, pin_policy_version=bound)

    # 4. Enforce the mandatory variance channel.
    ctx = result.get("execution_context")
    if ctx is None:
        raise MissingExecutionContextError(
            "callee returned no execution_context; cannot confirm which "
            "policy version produced this result. Treating as contract breach."
        )
    if ctx.get("policy_version") != bound:
        # Callee executed under a different version than the warrant bound.
        # This is the exact silent-drift failure; reject the result.
        raise PolicyVersionMismatchError(
            f"callee executed under policy_version={ctx.get('policy_version')!r} "
            f"but warrant bound {bound!r}; result is semantically stale."
        )

    result["_pinned_old_policy"] = pinned_old
    return result
