# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-warrant-replay-window-in-cross-org-signed-agent-manifests.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-warrant-replay-window-in-cross-org-signed-agent-manifests.warrant.json
# Markdown SHA-256:   f493f4b7b0dc20165f50319925eea53f84a40da00cbb8afdc8e95d3467d3514c
# Code AST SHA-256:   d07e50b64a593c8c294e6cfe9bf5be26c59207c1fb58fcc38d1fffdae73d4596
# Verified Classes:   WarrantTopologyError, Manifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class WarrantTopologyError(RuntimeError):
    """Raised when a signed manifest is cryptographically valid but
    topologically unauthorized for the presenting verifier."""


@dataclass(frozen=True)
class Manifest:
    iss: str
    sub: str
    aud: FrozenSet[str]
    scope: str
    jti: str
    delegation_depth: int
    may_redelegate: bool
    nbf: int
    exp: int


def verify_warrant(
    manifest: Manifest,
    verifier_org: str,
    presented_identity: str,
    transport_identity: str,
    hops_traversed: int,
    consumed_jti_ledger: FrozenSet[str],
    now: int,
    clock_skew: int = 30,
) -> None:
    # Cryptographic predicate (assumed already checked upstream for signature).
    if not (manifest.nbf - clock_skew <= now <= manifest.exp + clock_skew):
        raise WarrantTopologyError(
            f"warrant {manifest.jti} outside validity window"
        )

    # Topological predicate — the federation boundary.
    if verifier_org not in manifest.aud:
        raise WarrantTopologyError(
            f"audience mismatch: verifier {verifier_org} not in aud={set(manifest.aud)} "
            f"for jti={manifest.jti}; delegate attempted cross-verifier replay"
        )
    if presented_identity != transport_identity:
        raise WarrantTopologyError(
            f"sub/transport identity divergence: manifest claims {presented_identity}, "
            f"transport authenticates {transport_identity}"
        )
    if hops_traversed > 0 and not manifest.may_redelegate:
        raise WarrantTopologyError(
            f"redelegation forbidden: may_redelegate=false but hops_traversed={hops_traversed} "
            f"for jti={manifest.jti}"
        )
    if manifest.delegation_depth - hops_traversed < 0:
        raise WarrantTopologyError(
            f"delegation depth exhausted: depth={manifest.delegation_depth}, "
            f"hops={hops_traversed}"
        )
    if manifest.jti in consumed_jti_ledger:
        raise WarrantTopologyError(
            f"jti replay: {manifest.jti} already consumed in federation ledger; "
            f"refusing second presentation at {verifier_org}"
        )
