# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-trust-anchor-re-anchoring-loss-during-cross-org-policy-negotiation-before-capability-grants-are-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-trust-anchor-re-anchoring-loss-during-cross-org-policy-negotiation-before-capability-grants-are-committed.warrant.json
# Markdown SHA-256:   3e5b478caa07b381c919c4a433d3e17f4ba9628d06b2beccbcb2cc4b6c3e3089
# Code AST SHA-256:   66cf7dad45780403616f5769ad0e762dcd3b9f6d49bc9525c0ae6b95a109dbcd
# Verified Classes:   TrustAnchorReanchoringError, PolicyProfile, NegotiationSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TrustAnchorReanchoringError(RuntimeError):
    """Raised when a capability grant is signed under an anchor that is not in
    the delegation lineage of the anchor that accepted the negotiated envelope."""
    pass


@dataclass
class PolicyProfile:
    data_class_extensions: frozenset
    scope_restrictions: dict


@dataclass
class NegotiationSession:
    session_id: str
    accepting_anchor_fp: Optional[str] = None
    accepted_envelope: Optional[dict] = None
    # delegation closure: anchor_fp -> set of descendant anchor_fps
    delegation_closure: dict = field(default_factory=dict)
    anchor_profiles: dict = field(default_factory=dict)


def record_envelope_acceptance(session: NegotiationSession, anchor_fp: str, envelope: dict) -> None:
    if session.accepting_anchor_fp is not None:
        raise TrustAnchorReanchoringError(
            f"session {session.session_id} already pinned to {session.accepting_anchor_fp}"
        )
    session.accepting_anchor_fp = anchor_fp
    session.accepted_envelope = envelope


def _in_lineage(session: NegotiationSession, signing_anchor_fp: str) -> bool:
    root = session.accepting_anchor_fp
    if signing_anchor_fp == root:
        return True
    return signing_anchor_fp in session.delegation_closure.get(root, set())


def _profile_is_superset(session: NegotiationSession, signing_anchor_fp: str) -> bool:
    accepting = session.anchor_profiles.get(session.accepting_anchor_fp)
    signing = session.anchor_profiles.get(signing_anchor_fp)
    if accepting is None or signing is None:
        return False
    if not accepting.data_class_extensions.issubset(signing.data_class_extensions):
        return False
    for scope, required in accepting.scope_restrictions.items():
        if scope not in signing.scope_restrictions:
            return False
        if required not in signing.scope_restrictions[scope]:
            return False
    return True


def validate_grant_lineage(session: NegotiationSession, signing_anchor_fp: str, grant: dict) -> None:
    if session.accepting_anchor_fp is None:
        raise TrustAnchorReanchoringError(
            f"session {session.session_id} has no pinned accepting anchor; grant cannot be lineage-checked"
        )
    if not _in_lineage(session, signing_anchor_fp):
        raise TrustAnchorReanchoringError(
            f"grant signed under {signing_anchor_fp} is not in delegation closure of "
            f"accepting anchor {session.accepting_anchor_fp}; sibling re-anchor detected — "
            f"abort and renegotiate envelope"
        )
    if signing_anchor_fp != session.accepting_anchor_fp and not _profile_is_superset(
        session, signing_anchor_fp
    ):
        raise TrustAnchorReanchoringError(
            f"descendant anchor {signing_anchor_fp} profile is not a superset of accepting "
            f"anchor {session.accepting_anchor_fp} constraints; grant would downgrade "
            f"negotiated data-class or scope restrictions"
        )
    # lineage and superset both hold: safe to commit
    return None
