# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-multi-agent-federation-from-silently-degrading-trust-anchors-during-policy-renegotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-multi-agent-federation-from-silently-degrading-trust-anchors-during-policy-renegotiation.warrant.json
# Markdown SHA-256:   3cd5ff01da8d0fa5f7e696b6ee479be32bf5810d3b98ce41be94f3bbd9afae2a
# Code AST SHA-256:   c401cc8a179216bb94dc9387c6ce1987e2c2ae541d173db90fe157d5861e8b4e
# Verified Classes:   TrustAnchorCoherenceError, PolicyVersion, TrustAnchor, PolicyDelta
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class TrustAnchorCoherenceError(RuntimeError):
    """Raised when a trust anchor's embedded policy version is not coherent
    with the accepting side's currently active policy version."""


@dataclass(frozen=True)
class PolicyVersion:
    org: str
    version_id: str
    parents: tuple[str, ...]  # ancestry DAG edges within the org

    def is_ancestor_of(self, other: "PolicyVersion", known: dict[str, "PolicyVersion"]) -> bool:
        if self.org != other.org:
            return False
        if self.version_id == other.version_id:
            return True
        # Walk other's ancestry; treat self as ancestor if reachable.
        stack = list(other.parents)
        seen: set[str] = set()
        while stack:
            vid = stack.pop()
            if vid in seen:
                continue
            seen.add(vid)
            if vid == self.version_id:
                return True
            node: Optional[PolicyVersion] = known.get(vid)
            if node is not None:
                stack.extend(node.parents)
        return False


@dataclass(frozen=True)
class TrustAnchor:
    issuer: str
    subject: str
    policy_version: PolicyVersion
    signature_valid: bool
    revoked: bool


@dataclass(frozen=True)
class PolicyDelta:
    """Relative change between two versions on the issuing side."""
    is_narrowing: bool  # True if newer is a strict subset of older
    is_widening: bool   # True if newer grants anything the older did not


def check_anchor_coherence(
    anchor: TrustAnchor,
    active: PolicyVersion,
    known: dict[str, PolicyVersion],
    delta_from_anchor_to_active: PolicyDelta,
) -> None:
    """Enforce version-coherence at acceptance time.

    Validity (signature, revocation) is necessary but not sufficient.
    Coherence decides whether the anchor still speaks for the active policy.
    """
    if not anchor.signature_valid:
        raise TrustAnchorCoherenceError(
            f"anchor {anchor.issuer}->{anchor.subject}: invalid signature"
        )
    if anchor.revoked:
        raise TrustAnchorCoherenceError(
            f"anchor {anchor.issuer}->{anchor.subject}: revoked"
        )

    anchored = anchor.policy_version
    if anchored.version_id == active.version_id:
        return  # exact match, coherent

    if anchored.is_ancestor_of(active, known):
        # Anchor speaks for an ancestor of the active policy.
        if delta_from_anchor_to_active.is_widening:
            # Newer policy widened scope; the anchor holder never consented.
            raise TrustAnchorCoherenceError(
                f"anchor {anchor.issuer}->{anchor.subject}: ancestor "
                f"{anchored.version_id} cannot inherit widening change to "
                f"{active.version_id}; require re-issuance"
            )
        if delta_from_anchor_to_active.is_narrowing:
            # Safe to honor, but only under the intersection of the two.
            return
        raise TrustAnchorCoherenceError(
            f"anchor {anchor.issuer}->{anchor.subject}: ancestor "
            f"{anchored.version_id} vs active {active.version_id} with "
            f"undetermined delta; refuse to guess"
        )

    # Not an ancestor: either active is an ancestor of anchored (anchor is
    # newer than our policy — also incoherent for acceptance), or divergent.
    raise TrustAnchorCoherenceError(
        f"anchor {anchor.issuer}->{anchor.subject}: policy version "
        f"{anchored.version_id} is not an ancestor of active "
        f"{active.version_id}; possible policy fork, halt negotiation"
    )


def accept_anchor(
    anchor: TrustAnchor,
    active: PolicyVersion,
    known: dict[str, PolicyVersion],
    delta: PolicyDelta,
) -> str:
    check_anchor_coherence(anchor, active, known, delta)
    if anchor.policy_version.version_id == active.version_id:
        return "accepted"
    return "accepted_under_intersection"
