# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-trust-tiered-peer-message-before-sanitization-rather-than-after.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-trust-tiered-peer-message-before-sanitization-rather-than-after.warrant.json
# Markdown SHA-256:   af5b38ae1f38c64a7b5bf84bcd706760704c412ea54893d44d483f2c8d48e40b
# Code AST SHA-256:   105a552a60fb3a3f660e52ab4faffa10696b9ad30c4012d86264e7a24b26a319
# Verified Classes:   TierConfusionError, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TierConfusionError(RuntimeError):
    """Raised when a message's declared tier cannot be trusted because it is
    message-derived, or when the body-hash binding to the delegation chain
    fails. Signals that the message must be rejected, not downgraded."""


@dataclass(frozen=True)
class Envelope:
    transport_identity: str      # set by transport, not by peer
    declared_tier: str           # peer-authored, UNTRUSTED
    delegation_chain: bytes      # peer-authored
    chain_body_hash: bytes       # hash the chain claims to bind
    body: bytes                  # peer-authored, UNTRUSTED


# Local authority: the ONLY source of truth for tier. Keyed by transport
# identity, which the peer cannot forge.
LOCAL_TIER_TABLE = {
    "orchestrator.mtls": "trusted",
    "worker-7.mtls": "internal",
}


def resolve_tier_and_quarantine(env: Envelope) -> str:
    """Resolve tier from local state only; verify body binding. Returns the
    fixed tier, or raises TierConfusionError to force rejection."""
    # 1. Tier comes from transport identity, never from env.declared_tier.
    if env.transport_identity not in LOCAL_TIER_TABLE:
        raise TierConfusionError(
            f"unknown transport identity {env.transport_identity!r}; "
            "cannot resolve tier from message-derived fields"
        )
    tier = LOCAL_TIER_TABLE[env.transport_identity]

    # 2. The chain must bind the actual body, not just itself.
    actual = hashlib.sha256(env.body).digest()
    if env.chain_body_hash != actual:
        raise TierConfusionError(
            "delegation chain does not bind message body; possible replay"
        )

    # 3. If the peer's declared tier disagrees with local authority, that is
    #    itself an injection signal — reject rather than downgrade.
    if env.declared_tier != tier:
        raise TierConfusionError(
            f"declared tier {env.declared_tier!r} != local tier {tier!r}; "
            "tier-confusion injection suspected"
        )
    return tier


def ingest(env: Envelope) -> str:
    # Quarantine-first: resolve tier before any body parse or sanitize.
    tier = resolve_tier_and_quarantine(env)
    # Only now is it safe to sanitize under a fixed, non-message-derived tier.
    return sanitize(env.body, tier)


def sanitize(body: bytes, tier: str) -> str:
    # Policy is a pure function of (body, fixed tier). No tier reads here.
    text = body.decode("utf-8", errors="replace")
    if tier == "trusted":
        return text
    # internal/external: strip instruction blocks and tool directives.
    return text.replace("tool_call", "[stripped]").replace("orchestrator", "[redacted]")
