# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-taint-aware-retrieval-fail-at-the-trust-label-join-when-context-and-instructions-share-a-serialization-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-taint-aware-retrieval-fail-at-the-trust-label-join-when-context-and-instructions-share-a-serialization-channel.warrant.json
# Markdown SHA-256:   0826f73d4628c3128fe551b7c2b94c56447976eb53ec81a39a44b8c4845c39df
# Code AST SHA-256:   c50d9fcf702fa9ee430af4f909bdc296f88afedc291763787d8a838230a97ec2
# Verified Classes:   TaintChannelViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintChannelViolation(RuntimeError):
    """Raised when serialized prompt regions desync from provenance labels."""
    pass


REGION_TOKENS = ("[TRUST:", "[/TRUST]")


def serialize_chunk(chunk_id: str, body: str, trust: str) -> str:
    if trust not in ("internal", "external", "unknown"):
        raise TaintChannelViolation(f"chunk {chunk_id}: illegal trust label {trust!r}")
    # Gate 1: refuse inline serialization if content can forge region syntax.
    for tok in REGION_TOKENS:
        if tok in body:
            raise TaintChannelViolation(
                f"chunk {chunk_id}: body contains region-control token {tok!r}; "
                "route via escaped channel"
            )
    return f"[TRUST:{trust}] {body} [/TRUST]"


def assemble(chunks: list[tuple[str, str, str]], instruction: str) -> str:
    parts = [serialize_chunk(cid, body, trust) for cid, body, trust in chunks]
    parts.append(f"[TRUST:internal] {instruction} [/TRUST]")
    prompt = "\n".join(parts)
    audit_regions(prompt, chunks)
    return prompt


def audit_regions(prompt: str, chunks: list[tuple[str, str, str]]) -> None:
    # Gate 4: re-derive labels from the serialized string; fail closed on mismatch.
    expected = [trust for _, _, trust in chunks] + ["internal"]
    seen = []
    for line in prompt.splitlines():
        if line.startswith("[TRUST:"):
            seen.append(line[len("[TRUST:"):].split("]", 1)[0])
    if seen != expected:
        raise TaintChannelViolation(
            f"post-assembly region mismatch: expected {expected}, derived {seen}"
        )
