# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-whose-trust-anchor-was-re-signed-mid-negotiation-and-how-does-warrant-chain-for.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-whose-trust-anchor-was-re-signed-mid-negotiation-and-how-does-warrant-chain-for.warrant.json
# Markdown SHA-256:   ebaceccdd7304474f4d18222ff06d4dd197ca0f44ce194b19b2eb2969f049f17
# Code AST SHA-256:   9293993b7e5230044927796dd10666af611e2d45b87543037745798ec114e900
# Verified Classes:   WarrantForkError, AnchorBundle, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantForkError(RuntimeError):
    """Raised when a warrant's anchor identity diverges mid-negotiation."""
    pass


@dataclass(frozen=True)
class AnchorBundle:
    root_fingerprint: str
    bundle_hash: str
    # maps capability class -> set of permitted path globs
    expansion: dict


@dataclass(frozen=True)
class Warrant:
    scope: str                 # e.g. "filesystem.read:/shared"
    issued_under_bundle: str   # bundle_hash at mint time
    signature: str


def _expand(bundle: AnchorBundle, scope: str) -> frozenset:
    cls = scope.split(":", 1)[0]
    return frozenset(bundle.expansion.get(cls, ()))


def verify_federated_grant(
    warrant: Warrant,
    anchor_at_issue: AnchorBundle,
    anchor_at_verify: AnchorBundle,
    transcript_anchor_hashes: list,
) -> bool:
    # 1. Anchor identity must be stable across the transaction.
    if anchor_at_issue.bundle_hash != anchor_at_verify.bundle_hash:
        # Rotation happened. Only additive, non-predicate-changing rotations pass.
        issue_exp = _expand(anchor_at_issue, warrant.scope)
        verify_exp = _expand(anchor_at_verify, warrant.scope)
        if verify_exp < issue_exp:
            raise WarrantForkError(
                f"anchor rotated to narrow scope of {warrant.scope!r}: "
                f"issued_under={warrant.issued_under_bundle} "
                f"verify_under={anchor_at_verify.bundle_hash} "
                f"lost={sorted(issue_exp - verify_exp)}"
            )
        if warrant.issued_under_bundle != anchor_at_verify.bundle_hash:
            raise WarrantForkError(
                "warrant not re-minted after non-additive anchor rotation"
            )

    # 2. Root fingerprint must match even if bundle differs (defense in depth).
    if anchor_at_issue.root_fingerprint != anchor_at_verify.root_fingerprint:
        raise WarrantForkError("root key fingerprint changed mid-negotiation")

    # 3. Transcript must not contain more than one distinct bundle hash
    #    for this negotiation unless a re-mint is recorded.
    distinct = set(transcript_anchor_hashes)
    if len(distinct) > 1 and warrant.issued_under_bundle not in distinct:
        raise WarrantForkError(
            f"warrant bundle {warrant.issued_under_bundle} absent from "
            f"transcript anchors {sorted(distinct)}"
        )

    # 4. Signature check (stubbed; real impl verifies against root key).
    expected = hashlib.sha256(
        f"{warrant.scope}|{warrant.issued_under_bundle}".encode()
    ).hexdigest()
    if warrant.signature != expected:
        raise WarrantForkError("warrant signature invalid under resolved anchor")

    return True
