# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-when-a-tool-boundary-re-serializes-untrusted-content-into-a-trusted-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-when-a-tool-boundary-re-serializes-untrusted-content-into-a-trusted-schema.warrant.json
# Markdown SHA-256:   514f774c8befd37d9c0322e2ff96ead5fd470843250a9574d526ab68904677da
# Code AST SHA-256:   06f96ca529fe97a96f2afaa940de99947837acdc8606b3ef7d1ea588f6125c14
# Verified Classes:   TaintBoundaryViolation, Fragment, ToolResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TaintBoundaryViolation(RuntimeError):
    """Raised when a tool response crosses a boundary without a valid label manifest."""
    pass


@dataclass
class Fragment:
    content: str
    label: Optional[str] = None  # None means unlabeled -> quarantine


@dataclass
class ToolResponse:
    fragments: list[Fragment]
    manifest: Optional[dict] = None  # fragment_id -> label
    schema_valid: bool = False


def assert_label_manifest(resp: ToolResponse) -> None:
    """Boundary assertion: must run BEFORE schema validation promotes content."""
    if resp.manifest is None:
        raise TaintBoundaryViolation(
            "tool response has no label manifest; refusing to deserialize "
            "unlabeled content into planning context"
        )
    for idx, frag in enumerate(resp.fragments):
        fid = hashlib.sha256(frag.content.encode()).hexdigest()[:16]
        if fid not in resp.manifest:
            raise TaintBoundaryViolation(
                f"fragment {idx} (id={fid}) missing from manifest; "
                "content-addressed label cannot be recovered"
            )
        frag.label = resp.manifest[fid]
        if frag.label is None:
            raise TaintBoundaryViolation(
                f"fragment {idx} explicitly unlabeled; quarantine required"
            )


def deserialize_into_planner(resp: ToolResponse) -> list[Fragment]:
    assert_label_manifest(resp)
    if not resp.schema_valid:
        raise TaintBoundaryViolation("schema invalid after label check")
    # Only now may content enter planning context, with labels intact.
    return resp.fragments
