# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-cached-agent-card-when-the-skills-inputmodes-set-silently-narrows-between-discovery-and-task-submission.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-cached-agent-card-when-the-skills-inputmodes-set-silently-narrows-between-discovery-and-task-submission.warrant.json
# Markdown SHA-256:   7858210f41f80181f9a4aa83e6302f74a5557472425da2a7a5ee39eecdf69959
# Code AST SHA-256:   b42756453fb976f620b7ddad464982c8b4dcdb1b8f255ecbc920bd4db453b6e1
# Verified Classes:   CapabilityNarrowedError, ModeUnprovenError, SkillCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class CapabilityNarrowedError(RuntimeError):
    """Raised when a skill's inputModes set shrank between cached and live card."""
    pass


class ModeUnprovenError(RuntimeError):
    """Raised when a task's MIME type cannot be proven acceptable by the live agent."""
    pass


@dataclass(frozen=True)
class SkillCard:
    id: str
    input_modes: frozenset[str]
    output_modes: frozenset[str]

    def fingerprint(self) -> str:
        payload = "|".join(
            [self.id,
             ",".join(sorted(self.input_modes)),
             ",".join(sorted(self.output_modes))]
        )
        return hashlib.sha256(payload.encode()).hexdigest()


def validate_routing(
    cached: SkillCard,
    live: Optional[SkillCard],
    mime: str,
    narrowing_window_exceeded: bool,
) -> None:
    if mime not in cached.input_modes:
        raise ModeUnprovenError(
            f"mime {mime!r} not in cached skill {cached.id!r} inputModes"
        )
    if live is None:
        if narrowing_window_exceeded:
            raise ModeUnprovenError(
                f"cache stale beyond narrowing_window for skill {cached.id!r}; "
                f"live card required to prove {mime!r} acceptance"
            )
        return  # within window: route on cached membership
    narrowed = cached.input_modes - live.input_modes
    if narrowed:
        raise CapabilityNarrowedError(
            f"skill {cached.id!r} dropped inputModes {sorted(narrowed)} "
            f"between cache (fp={cached.fingerprint()[:12]}) and live "
            f"(fp={live.fingerprint()[:12]})"
        )
    if mime not in live.input_modes:
        raise ModeUnprovenError(
            f"mime {mime!r} absent from live skill {live.id!r} inputModes"
        )


def route_task(cached: SkillCard, live: Optional[SkillCard], mime: str,
               age_exceeded: bool) -> str:
    validate_routing(cached, live, mime, age_exceeded)
    return f"route:{cached.id}:{mime}"
