# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-federated-tool-registry-fail-open-when-its-trust-anchor-rotates-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-federated-tool-registry-fail-open-when-its-trust-anchor-rotates-mid-handshake.warrant.json
# Markdown SHA-256:   bd2ada60460ba25c3a3af643aeec434f85950c02dfac4f87906ba5345d632b9f
# Code AST SHA-256:   7a8d52f47a2d905f7823f4ca1ac22807ea4b722a4af22bd952a1f3e9ac5a54c8
# Verified Classes:   AnchorRotationMidSession, TrustBoundaryViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AnchorRotationMidSession(RuntimeError):
    """Raised when a resolved descriptor is signed by an anchor other than the
    one pinned at session establishment, but still chains to the same org DID.
    This is a recoverable rotation, NOT a forgery. Caller must re-federate."""
    def __init__(self, session_kid: str, descriptor_kid: str, org_did: str):
        self.session_kid = session_kid
        self.descriptor_kid = descriptor_kid
        self.org_did = org_did
        super().__init__(
            f"descriptor signed by {descriptor_kid} but session pinned "
            f"{session_kid} for org {org_did}; re-federation required"
        )


class TrustBoundaryViolation(RuntimeError):
    """Descriptor chains to a different org DID than the session anchor."""
    pass


def resolve_descriptor(
    session_anchor: dict,       # {"kid": ..., "org_did": ..., "valid_until": ...}
    descriptor_vc: dict,        # {"signing_kid": ..., "issuer_did": ..., "chain": [...]}
    now: float,
) -> dict:
    signing_kid = descriptor_vc["signing_kid"]
    issuer_did = descriptor_vc["issuer_did"]

    if issuer_did != session_anchor["org_did"]:
        raise TrustBoundaryViolation(
            f"descriptor issuer {issuer_did} != session org {session_anchor['org_did']}"
        )

    if now > session_anchor["valid_until"]:
        raise AnchorRotationMidSession(
            session_kid=session_anchor["kid"],
            descriptor_kid=signing_kid,
            org_did=issuer_did,
        )

    if signing_kid != session_anchor["kid"]:
        # Same org, different anchor: rotation, not forgery. Force re-federation.
        raise AnchorRotationMidSession(
            session_kid=session_anchor["kid"],
            descriptor_kid=signing_kid,
            org_did=issuer_did,
        )

    return descriptor_vc
