# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-boundary-prompt-injection-carrier-in-federated-agent-handoffs-and-where-the-trust-attestation-invariant-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-boundary-prompt-injection-carrier-in-federated-agent-handoffs-and-where-the-trust-attestation-invariant-fails.warrant.json
# Markdown SHA-256:   c63186177582028bb8bd182d3ac91c8cb566ae5b502dc8c10d27ae8c38ad399d
# Code AST SHA-256:   11706e33f7895191df247a804cb1af5f2171f42ae0f1b8f5de6906ff717d860e
# Verified Classes:   ProvenanceResetError, InstructionAdmissionError, Envelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUST_RANK = {"web": 0, "tool": 1, "peer": 2, "internal": 3, "system": 4}

class ProvenanceResetError(RuntimeError):
    """Raised when a forwarder contracts the provenance set across a trust seam."""
    pass

class InstructionAdmissionError(RuntimeError):
    """Raised when untrusted-origin content is admitted as an executable instruction."""
    pass

@dataclass(frozen=True)
class Envelope:
    sender: str
    provenance: FrozenSet[str]
    payload: str
    kind: str  # "data" or "instruction"

def forward(inbound: Envelope, outbound_provenance: FrozenSet[str], payload: str) -> Envelope:
    # Invariant: a forwarder may only accumulate provenance, never contract it.
    if not inbound.provenance.issubset(outbound_provenance):
        raise ProvenanceResetError(
            f"forwarder contracted provenance {set(inbound.provenance)} -> "
            f"{set(outbound_provenance)}; carrier signature detected at seam"
        )
    return Envelope(
        sender="forwarder",
        provenance=outbound_provenance,
        payload=payload,
        kind="data",  # forwarded content is always data until re-admitted
    )

def admit(env: Envelope, domain_threshold: int) -> Envelope:
    min_rank = min(TRUST_RANK.get(p, -1) for p in env.provenance)
    if env.kind == "instruction" and min_rank < domain_threshold:
        raise InstructionAdmissionError(
            f"instruction admitted from provenance {set(env.provenance)} "
            f"(min rank {min_rank} < threshold {domain_threshold})"
        )
    if min_rank < domain_threshold:
        return Envelope(env.sender, env.provenance, env.payload, kind="data")
    return env
