# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-trust-anchor-rollover-during-cross-org-mcp-federation-handshakes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-trust-anchor-rollover-during-cross-org-mcp-federation-handshakes.warrant.json
# Markdown SHA-256:   d487c20831de5ddc4aa548d7181bb940e484805aa08e5834ae864031f7e34c98
# Code AST SHA-256:   1ce87337a0145dd310182d5b04f6b3059b4a232fb69bc127185e2a0072430853
# Verified Classes:   StaleAnchorError, SplitAnchorSessionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StaleAnchorError(RuntimeError):
    """Raised when a federated MCP handshake terminates at a trust anchor
    that is present in the local store but not confirmed current for new
    sessions. This is the silent-rollover boundary: the chain is valid,
    but the terminal key is retired."""
    pass


class SplitAnchorSessionError(RuntimeError):
    """Raised when a downstream warrant is issued under a different anchor
    than the one the session was established under."""
    pass


def establish_federated_session(chain, local_store, current_anchor_assertion, handshake_nonce):
    # Walk the chain to its terminal root.
    terminal = chain.root()
    fingerprint = terminal.fingerprint()

    # Loud case: unknown root.
    if fingerprint not in local_store:
        raise StaleAnchorError(
            f"anchor {fingerprint} not present in local store; cannot trust chain"
        )

    # Silent-rollover case: root is present but may be retired.
    entry = local_store[fingerprint]
    if entry.status == "retired":
        # Must independently confirm currency via a fresh, nonce-bound assertion.
        # The chain itself cannot answer this question.
        if current_anchor_assertion is None:
            raise StaleAnchorError(
                f"anchor {fingerprint} is retired and no current-anchor "
                f"assertion was supplied; refusing to open new session"
            )
        if current_anchor_assertion.nonce != handshake_nonce:
            raise StaleAnchorError(
                f"current-anchor assertion nonce mismatch for {fingerprint}; "
                f"assertion is not bound to this handshake"
            )
        if current_anchor_assertion.active_fingerprint != fingerprint:
            raise StaleAnchorError(
                f"anchor {fingerprint} is retired; remote currently asserts "
                f"{current_anchor_assertion.active_fingerprint} as authoritative"
            )

    # Invariant: session records the exact anchor it was established under.
    return {
        "session_id": handshake_nonce,
        "anchor_fingerprint": fingerprint,
        "anchor_status": entry.status,
    }


def verify_warrant_against_session(warrant, session):
    # The split-anchor invariant: warrant issuing anchor must equal
    # the session's recorded anchor fingerprint.
    if warrant.issuing_anchor_fingerprint != session["anchor_fingerprint"]:
        raise SplitAnchorSessionError(
            f"warrant issued under {warrant.issuing_anchor_fingerprint} but "
            f"session {session['session_id']} was established under "
            f"{session['anchor_fingerprint']}; refusing to execute"
        )
    if not warrant.verify_signature():
        raise SplitAnchorSessionError(
            f"warrant signature invalid for session {session['session_id']}"
        )
    return True
