# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-handoff-whose-trust-anchor-was-re-signed-mid-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-handoff-whose-trust-anchor-was-re-signed-mid-negotiation.warrant.json
# Markdown SHA-256:   81576fbd01efc240a474858251fb917e69838a63243f9cdeff881a65a28d8901
# Code AST SHA-256:   919fa313942b203f78d8173a1578972e8d50f48bdc1c75013f623bbf20b18c10
# Verified Classes:   AnchorRotationMidHandoff, Grant, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AnchorRotationMidHandoff(RuntimeError):
    """Raised when a capability grant's pinned trust anchor is no longer the
    anchor the executor enforces, and the grant cannot be safely reconciled."""


@dataclass(frozen=True)
class Grant:
    anchor_fingerprint: str          # sha256 of the pinned public key
    manifest_hash: str
    clause_ids: frozenset[str]      # opaque, anchor-scoped
    scope: str


@dataclass(frozen=True)
class Manifest:
    anchor_fingerprint: str
    manifest_hash: str
    clause_ids: frozenset[str]
    supersedes: dict[str, str]       # old_clause_id -> new_clause_id, owner-authored


def verify_and_reconcile(grant: Grant, current: Manifest) -> frozenset[str]:
    # Case 1: same anchor, different manifest content -> key misuse, never reconcile.
    if grant.anchor_fingerprint == current.anchor_fingerprint:
        if grant.manifest_hash != current.manifest_hash:
            raise AnchorRotationMidHandoff(
                "same anchor signed divergent manifests; refusing to reconcile"
            )
        return grant.clause_ids

    # Case 2: anchor rotated. Only an owner-authored supersession table is
    # admissible; similarity inference is forbidden.
    if not current.supersedes:
        raise AnchorRotationMidHandoff(
            f"anchor rotated {grant.anchor_fingerprint} -> "
            f"{current.anchor_fingerprint} with no signed supersession table"
        )

    mapped = set()
    for cid in grant.clause_ids:
        if cid not in current.supersedes:
            raise AnchorRotationMidHandoff(
                f"grant clause {cid!r} has no owner-authored supersession; "
                "inference-based mapping is prohibited"
            )
        mapped.add(current.supersedes[cid])

    # Every mapped clause must exist in the new manifest; a dangling target
    # means the supersession table is stale or forged.
    missing = mapped - current.clause_ids
    if missing:
        raise AnchorRotationMidHandoff(
            f"supersession targets absent from manifest: {sorted(missing)}"
        )
    return frozenset(mapped)
