# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-cross-agent-taint-propagation-has-crossed-a-delegation-boundary-undetected.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-cross-agent-taint-propagation-has-crossed-a-delegation-boundary-undetected.warrant.json
# Markdown SHA-256:   bace1024713d0cd1c3621912a7d76da168fc09c27a270c691944b72639a5f252
# Code AST SHA-256:   4782d775d518073d7b062907ad5bcd8c15507242d2102b5540796cf0d5facea3
# Verified Classes:   TaintBoundaryViolation, Span, Envelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintBoundaryViolation(RuntimeError):
    """Raised when tainted content crosses a delegation hop without its label."""


@dataclass
class Span:
    text: str
    tainted: bool
    wrapped: bool = False
    mood: str = "quoted"  # "quoted" | "imperative"

    def digest(self) -> str:
        return hashlib.sha256(self.text.strip().encode()).hexdigest()[:16]


@dataclass
class Envelope:
    free_text: str
    spans: list[Span] = field(default_factory=list)
    rendered_fields: set[str] = field(default_factory=set)


def reconcile_hop(outbound: Envelope, inbound: Envelope) -> None:
    """Enforce taint conservation across one delegation boundary.

    Invariant: every tainted span in `outbound` must appear in `inbound`
    either wrapped, or absent (replaced by a summary token). Never present
    unwrapped in free text. Additionally, mood may not escalate.
    """
    inbound_by_hash = {s.digest(): s for s in inbound.spans}

    for span in outbound.spans:
        if not span.tainted:
            continue
        received = inbound_by_hash.get(span.digest())

        # Case (b): span dropped entirely — acceptable only if summarized.
        if received is None:
            if span.digest() not in inbound.free_text:
                continue
            # Content survived in free text but no Span object carried the label.
            raise TaintBoundaryViolation(
                f"tainted span {span.digest()!r} present in free text of hop "
                f"with no provenance annotation — label dropped at serialization"
            )

        # Case (a): span present — must be wrapped.
        if not received.wrapped:
            raise TaintBoundaryViolation(
                f"tainted span {span.digest()!r} rendered unwrapped into "
                f"receiving prompt (fields={inbound.rendered_fields})"
            )

        # Authority-inflation check: rising force, falling provenance.
        if span.mood == "quoted" and received.mood == "imperative":
            raise TaintBoundaryViolation(
                f"authority inflation on {span.digest()!r}: quoted->imperative "
                f"across hop; quarantine receiving agent"
            )


def delegate(outbound: Envelope, inbound: Envelope) -> None:
    try:
        reconcile_hop(outbound, inbound)
    except TaintBoundaryViolation:
        # Fail closed: strip write/delete tools, substitute typed placeholders.
        raise
