# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-federation-trust-anchors-from-silently-degrading-to-transitive-trust-after-a-policy-renegotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-federation-trust-anchors-from-silently-degrading-to-transitive-trust-after-a-policy-renegotiation.warrant.json
# Markdown SHA-256:   5e91f56cfa8330b42f1c0e06246596f6f2ad437e20daf3d10dcaa5fcec9b4d3b
# Code AST SHA-256:   68adb9141cc523e03cf53467971005d5cabd611b88cf819bce06b12e1bc5b82d
# Verified Classes:   AnchorScopeViolation, FederatedSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AnchorScopeViolation(RuntimeError):
    """Raised when a renegotiation response would change the session's
    effective trust anchor away from the fingerprint pinned at session open."""
    pass


class FederatedSession:
    def __init__(self, peer_id: str, pinned_anchor_fp: str, policy: dict):
        self.peer_id = peer_id
        self.pinned_anchor_fp = pinned_anchor_fp
        self.policy = policy
        self.effective_anchor_fp = pinned_anchor_fp
        self.state = "open"

    def _validate_chain_against_pin(self, chain_leaf_fp: str, chain_root_fp: str) -> None:
        # Invariant: the chain presented in ANY frame must terminate at the
        # anchor pinned at session open. Peer-of-peer roots are NOT acceptable
        # here even if present in the global trust store.
        if chain_root_fp != self.pinned_anchor_fp:
            raise AnchorScopeViolation(
                f"peer={self.peer_id} presented chain rooted at {chain_root_fp!r} "
                f"but session is pinned to {self.pinned_anchor_fp!r}; "
                f"renegotiation cannot re-anchor a live session"
            )
        if chain_leaf_fp != self.pinned_anchor_fp and chain_root_fp != chain_leaf_fp:
            # leaf may be a sub-anchor, but only if root matches pin (checked above)
            pass

    def apply_renegotiation(self, response: dict) -> None:
        # Schema guard: renegotiation responses MUST NOT carry a warrant chain.
        if "warrant_chain" in response or "anchor" in response:
            raise AnchorScopeViolation(
                f"peer={self.peer_id} attempted to mutate anchor via renegotiation; "
                f"re-delegation requires a new session with explicit re-pinning"
            )
        chain_root = response.get("chain_root_fp")
        chain_leaf = response.get("chain_leaf_fp")
        if chain_root is not None:
            self._validate_chain_against_pin(chain_leaf, chain_root)
        # Only policy fields may change.
        new_policy = response.get("policy")
        if not isinstance(new_policy, dict):
            raise AnchorScopeViolation(
                f"peer={self.peer_id} renegotiation missing policy bundle"
            )
        # Originator-side re-verification of non-delegable constraints.
        for key in ("data_residency", "tool_scope_ceiling"):
            if key in self.policy and new_policy.get(key) != self.policy[key]:
                raise AnchorScopeViolation(
                    f"peer={self.peer_id} renegotiation would widen {key} "
                    f"from {self.policy[key]!r} to {new_policy.get(key)!r}; "
                    f"requires explicit reanchor event"
                )
        self.policy = new_policy

    def reanchor(self, new_anchor_fp: str, auditor_approved: bool) -> None:
        # The ONLY legitimate path to change the effective anchor.
        if not auditor_approved:
            raise AnchorScopeViolation(
                f"reanchor of peer={self.peer_id} from {self.pinned_anchor_fp!r} "
                f"to {new_anchor_fp!r} requires auditor approval"
            )
        self.pinned_anchor_fp = new_anchor_fp
        self.effective_anchor_fp = new_anchor_fp
        # caller is responsible for emitting an anchor-transition audit record
        # with before/after fingerprints; failure to do so is itself a bug.
