# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-capability-advertisement-it-cannot-verify-stale-trust-epochs-in-cross-org-multi-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-capability-advertisement-it-cannot-verify-stale-trust-epochs-in-cross-org-multi-agent-federation.warrant.json
# Markdown SHA-256:   8e5fcaba7c62d74036401ec9307ba2e7444ebeed6478e842e258e7ba641f0f2d
# Code AST SHA-256:   76402fbaa6e8a9bb6379a242672ba2f7139cc64b90885d7bc7849a5a5d080289
# Verified Classes:   StaleTrustEpochError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleTrustEpochError(RuntimeError):
    """Raised when a capability advertisement's signing epoch does not
    cover the verifier's current policy epoch for that capability class."""
    pass


def select_usable_advertisement(
    capability: str,
    advertisements: list[dict],
    trust_store: dict[str, set[str]],   # key_id -> set of authorized policy epochs
    current_policy_epoch: dict[str, str],  # capability_class -> epoch
    capability_class: str,
) -> dict:
    """Epoch-strict selection: return the advertisement whose signing epoch
    is the narrowest superset of the verifier's current policy epoch.

    Raises StaleTrustEpochError if no advertisement qualifies. This is a
    planning-time refusal, not a negotiation-time rejection.
    """
    required_epoch = current_policy_epoch.get(capability_class)
    if required_epoch is None:
        raise StaleTrustEpochError(
            f"no current policy epoch for capability class {capability_class!r}"
        )

    candidates = []
    for ad in advertisements:
        if ad.get("capability") != capability:
            continue
        key_id = ad.get("signing_key_id")
        authorized = trust_store.get(key_id, set())
        if required_epoch not in authorized:
            # Signature may be valid, but the key's authorization does not
            # cover our current epoch. Refuse to plan against it.
            continue
        candidates.append(ad)

    if not candidates:
        raise StaleTrustEpochError(
            f"capability {capability!r} has no advertisement whose signing "
            f"epoch covers required epoch {required_epoch!r}; refusing to plan"
        )

    # Prefer the advertisement with the fewest authorized epochs (narrowest
    # superset) to avoid planning on a broader-than-necessary authorization.
    candidates.sort(
        key=lambda ad: len(trust_store.get(ad["signing_key_id"], set()))
    )
    return candidates[0]


def plan_workflow(
    capability: str,
    advertisements: list[dict],
    trust_store: dict[str, set[str]],
    current_policy_epoch: dict[str, str],
    capability_class: str,
) -> dict:
    try:
        ad = select_usable_advertisement(
            capability, advertisements, trust_store,
            current_policy_epoch, capability_class,
        )
    except StaleTrustEpochError:
        # Invalidate cache and surface the refusal to the planner.
        raise
    return {"capability": capability, "advertisement": ad, "status": "planned"}
