# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-policy-bounded-trust-anchor-when-a-federated-peer-renegotiates-capability-scope-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-policy-bounded-trust-anchor-when-a-federated-peer-renegotiates-capability-scope-mid-session.warrant.json
# Markdown SHA-256:   97aafd5ef8c59aed1db8e3688e0bb5aba10a43c9636a7bf96dc4cbaf0d697db8
# Code AST SHA-256:   665a1f45908586a291b1f91fcb1a467dcf855aea48581c4d482fb986a845b7dd
# Verified Classes:   TrustAnchorSeveredError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TrustAnchorSeveredError(RuntimeError):
    """Raised when a capability rebind would sever the session's policy-bounded trust anchor."""


def rebind_capability(anchor, prior_cap, new_cap):
    # anchor: the signed warrant W_A; prior_cap: C_old; new_cap: C_new from peer
    if new_cap.get("delegated_to_anchor") is None:
        # Peer omitted a field without declaring delegation; we cannot
        # safely inherit from prior_cap -- that is the anchor-severing move.
        raise TrustAnchorSeveredError(
            f"capability {new_cap.get('id')} omits constraints without "
            f"delegated_to_anchor flag; refusing rebind to avoid inheriting "
            f"stale values from {prior_cap.get('id')}"
        )

    effective = {}
    for field, anchor_bound in anchor["constraints"].items():
        declared = new_cap["constraints"].get(field)
        if declared is None:
            # Omitted: bound lives in the anchor, NOT in prior_cap.
            effective[field] = anchor_bound
        elif declared > anchor_bound:
            # Peer attempting to expand beyond the anchor: protocol violation.
            raise TrustAnchorSeveredError(
                f"capability {new_cap.get('id')} declares {field}={declared} "
                f"exceeding anchor ceiling {anchor_bound}; rebind rejected"
            )
        else:
            effective[field] = declared
    return effective


def apply_renegotiation(session, frame):
    try:
        session.effective = rebind_capability(
            session.anchor, session.capability, frame["capability"]
        )
    except TrustAnchorSeveredError as e:
        session.abort(reason=str(e))
        raise
