# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-escalate-its-trust-tier-on-a-replayed-warrant-and-then-route-privileged-payloads-to-a-peer-that-never-held-the-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-escalate-its-trust-tier-on-a-replayed-warrant-and-then-route-privileged-payloads-to-a-peer-that-never-held-the-grant.warrant.json
# Markdown SHA-256:   48c5c20ef1b96d3bdacb0a2e01c61381336b37a6539f0add3d50e2caabc83c9d
# Code AST SHA-256:   b8691042b585a6a81024798f7a2821e416be4aff992830af967c0d30e02492c7
# Verified Classes:   WarrantReplayEscalationError, Warrant, AgentState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class WarrantReplayEscalationError(RuntimeError):
    """Raised when a warrant is used to escalate a presenter's tier
    without subject binding, durable nonce consumption, or scope narrowing."""

@dataclass(frozen=True)
class Warrant:
    issuer: str
    sub: str          # the agent the grant is ABOUT
    aud: str          # intended delegation recipient
    scope: frozenset
    tier: int
    nonce: str
    exp: int

@dataclass
class AgentState:
    agent_id: str
    local_tier: int
    local_scope: frozenset
    consumed_nonces: set  # MUST be durable across restarts

def authorize_emission(
    presenter: AgentState,
    authenticated_identity: str,
    warrant: Optional[Warrant],
    requested_scope: frozenset,
    requested_tier: int,
    now: int,
    nonce_store: set,
) -> dict:
    # 1. Subject binding: warrant is evidence about sub, not a grant to holder.
    if warrant is not None and warrant.sub != authenticated_identity:
        # Presenter is relaying someone else's warrant; may act on_behalf_of sub,
        # but must NOT escalate its own tier from it.
        if warrant.exp < now:
            raise WarrantReplayEscalationError(
                f"expired warrant {warrant.nonce} presented by {presenter.agent_id}"
            )
        if warrant.nonce in nonce_store:
            raise WarrantReplayEscalationError(
                f"replayed warrant {warrant.nonce} (durable nonce check)"
            )
        nonce_store.add(warrant.nonce)
        # Narrowing: emitted authority <= warrant scope, tier never raised.
        allowed_scope = presenter.local_scope & warrant.scope
        allowed_tier = min(presenter.local_tier, warrant.tier)
        if not requested_scope <= allowed_scope:
            raise WarrantReplayEscalationError(
                f"scope widening: requested {requested_scope} exceeds "
                f"{allowed_scope} for on_behalf_of={warrant.sub}"
            )
        if requested_tier > allowed_tier:
            raise WarrantReplayEscalationError(
                f"tier escalation: requested {requested_tier} > {allowed_tier}"
            )
        return {"on_behalf_of": warrant.sub, "warrant_nonce": warrant.nonce,
                "tier": allowed_tier, "scope": allowed_scope}

    # 2. No warrant: act only under own durable authority.
    if requested_tier > presenter.local_tier:
        raise WarrantReplayEscalationError(
            f"{presenter.agent_id} requested tier {requested_tier} "
            f"without a bound warrant"
        )
    if not requested_scope <= presenter.local_scope:
        raise WarrantReplayEscalationError(
            f"{presenter.agent_id} requested scope outside local grant"
        )
    return {"on_behalf_of": presenter.agent_id, "warrant_nonce": None,
            "tier": presenter.local_tier, "scope": presenter.local_scope}
