# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-policy-attestation-when-the-trust-broker-s-warrant-chain-has-silently-re-anchored-across.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-policy-attestation-when-the-trust-broker-s-warrant-chain-has-silently-re-anchored-across.warrant.json
# Markdown SHA-256:   628e7c2a9ef328685f897b17d330b705dcd375a82fda8589316b08ee9a861f0c
# Code AST SHA-256:   1734114562044d0b2d282c19c5edbcc39293da439655ca6887656d2a6b0e544c
# Verified Classes:   WarrantContinuityError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class WarrantContinuityError(RuntimeError):
    """Raised when a re-issued warrant cannot be proven continuous with the cached warrant."""
    pass


SCOPE_FIELDS = (
    "issuer_root_fingerprint",
    "policy_payload_hash",
    "delegation_ceiling",
    "jurisdiction_scope",
    "validity_window",
    "subdelegable_capabilities",
)


def verify_warrant_continuity(cached_warrant: dict, presented_warrant: dict,
                              rotation_record: dict | None,
                              trusted_roots: set[str]) -> bool:
    # Fast path: payload hash match is necessary but NEVER sufficient.
    if cached_warrant["policy_payload_hash"] != presented_warrant["policy_payload_hash"]:
        return False

    if rotation_record is None:
        # No signed supersession claim: cannot distinguish re-sign from scope mutation.
        raise WarrantContinuityError(
            "re-issued warrant presented with no rotation record; "
            "payload hash matches but warrant scope continuity is unprovable"
        )

    if rotation_record.get("supersedes") != cached_warrant["warrant_id"]:
        raise WarrantContinuityError(
            f"rotation record supersedes {rotation_record.get('supersedes')!r}, "
            f"not cached warrant {cached_warrant['warrant_id']!r}"
        )

    if rotation_record["signing_root"] not in trusted_roots:
        raise WarrantContinuityError(
            "rotation record is signed by an untrusted root; "
            "supersession claim cannot be relied upon"
        )

    deltas = {
        f: (cached_warrant[f], presented_warrant[f])
        for f in SCOPE_FIELDS
        if cached_warrant[f] != presented_warrant[f]
    }

    if deltas:
        # A scope contraction is legitimate broker action but invalidates
        # any sub-delegation already performed under the broader scope.
        contracted = any(
            f == "delegation_ceiling" and new < old
            for f, (old, new) in deltas.items()
        )
        if contracted:
            raise WarrantContinuityError(
                f"mid-task scope contraction in fields {sorted(deltas)}; "
                "in-flight sub-delegations are orphaned and must be unwound"
            )
        raise WarrantContinuityError(
            f"rotation record claims empty scope delta but fields differ: {sorted(deltas)}"
        )

    return True


def gate_subdelegation(warrant: dict, requested_depth: int) -> None:
    # Re-read the ceiling at the moment of sub-delegation, not from task-start cache.
    if requested_depth > warrant["delegation_ceiling"]:
        raise WarrantContinuityError(
            f"sub-delegation depth {requested_depth} exceeds live ceiling "
            f"{warrant['delegation_ceiling']} on warrant {warrant['warrant_id']}"
        )
