# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-a2a-task-when-the-remote-agent-card-advertises-a-capability-the-local-planner-has-already-cached.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-a2a-task-when-the-remote-agent-card-advertises-a-capability-the-local-planner-has-already-cached.warrant.json
# Markdown SHA-256:   2cf314c97902e193f960711ad7dcc9bd8982873397b83ebcc6c7fe5ea22d2edf
# Code AST SHA-256:   e6d0ae2704b5bc20bf4c6f7f40932ba663d39c16ecc2b18ac9387a7522aca1f7
# Verified Classes:   StaleCardBehavioralDrift
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleCardBehavioralDrift(RuntimeError):
    """Raised when dispatch would rely on a cached card whose behavioral
    fingerprint no longer matches the ledger entry for the target skill."""
    pass


def gate_dispatch(ledger, agent_url, skill_id, cached_card, probe_hash=None):
    key_version = (agent_url, skill_id, cached_card["version"])
    entry = ledger.get(key_version)

    # No failure history under this card version: card trust is warranted.
    if entry is None or entry["failures"] == 0:
        return {"dispatch": True, "reason": "clean-ledger"}

    # Failure history exists. We need a behavioral fingerprint to decide.
    fingerprint = probe_hash or cached_card.get("signatures", [{}])[0].get("value")
    if fingerprint is None:
        # Unverifiable card + known failures = boundary crossed.
        # Do NOT dispatch on card trust; require probe or fallback.
        raise StaleCardBehavioralDrift(
            f"skill {skill_id}@{agent_url} v{cached_card['version']} has "
            f"{entry['failures']} failures and no behavioral fingerprint; "
            f"refusing card-trust dispatch, probe or fallback required"
        )

    if entry.get("fingerprint") == fingerprint:
        # Same runtime that failed before: retry is not warranted.
        raise StaleCardBehavioralDrift(
            f"fingerprint {fingerprint} already failed {entry['failures']}x "
            f"for {skill_id}@{agent_url}; card version unchanged, runtime unchanged"
        )

    # Fingerprint changed: runtime moved, clear stale entry, allow dispatch.
    ledger.pop(key_version, None)
    return {"dispatch": True, "reason": "fingerprint-transition", "fingerprint": fingerprint}
