# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-at-the-tool-serialization-boundary-and-re-admit-injected-instructions-as-trusted-context.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-at-the-tool-serialization-boundary-and-re-admit-injected-instructions-as-trusted-context.warrant.json
# Markdown SHA-256:   65071ee8fa281524b1d100b91f9af445181e00b4c091f37c955c4e7341cb4e89
# Code AST SHA-256:   2b513cef2edb734d27102fe65306d268138102fc7d47d53a1db431c661f7d57d
# Verified Classes:   Taint, TaintDissolutionError, LabeledSpan, LabelRegistry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum

class Taint(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"

class TaintDissolutionError(RuntimeError):
    """Raised when a transformation would silently drop or downgrade a taint label."""

@dataclass
class LabeledSpan:
    content: str
    taint: Taint
    def key(self) -> str:
        # Transformation-stable key: normalized content hash, not byte offsets.
        norm = " ".join(self.content.split())
        return hashlib.sha256(norm.encode()).hexdigest()

@dataclass
class LabelRegistry:
    spans: dict = field(default_factory=dict)

    def register(self, span: LabeledSpan) -> None:
        self.spans[span.key()] = span.taint

    def lookup(self, content: str) -> Taint:
        k = LabeledSpan(content, Taint.TRUSTED).key()
        # Fail-closed: unresolved content is UNTRUSTED, never TRUSTED.
        return self.spans.get(k, Taint.UNTRUSTED)

def serialize_tool_result(result: str, registry: LabelRegistry) -> LabeledSpan:
    """JSON re-encoding changes bytes; label must be re-derived from content."""
    import json
    encoded = json.dumps({"result": result})
    taint = registry.lookup(result)
    # Re-register under the encoded form so downstream lookups resolve.
    span = LabeledSpan(encoded, taint)
    registry.register(span)
    return span

def summarize(span: LabeledSpan, registry: LabelRegistry) -> LabeledSpan:
    """Lossy transform. Union semantics: summary inherits input taint."""
    summary = span.content[:64] + "..."
    if span.taint is Taint.UNTRUSTED:
        out = LabeledSpan(summary, Taint.UNTRUSTED)
    else:
        # Even trusted input summarized becomes UNTRUSTED unless re-verified,
        # because the summary is model-generated and not byte-faithful.
        out = LabeledSpan(summary, Taint.UNTRUSTED)
    registry.register(out)
    return out

def guarded_tool_call(arg_span: LabeledSpan, registry: LabelRegistry,
                       declassify_ledger: set) -> str:
    resolved = registry.lookup(arg_span.content)
    if resolved is Taint.UNTRUSTED and arg_span.key() not in declassify_ledger:
        raise TaintDissolutionError(
            f"Refusing side-effecting call: argument span {arg_span.key()[:12]} "
            f"is UNTRUSTED with no declassification ledger entry. "
            f"This is the injection-laundering boundary."
        )
    return "executed"
