# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-sanitize-tool-output-at-the-point-of-consumption-rather-than-at-the-point-of-ingestion.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-sanitize-tool-output-at-the-point-of-consumption-rather-than-at-the-point-of-ingestion.warrant.json
# Markdown SHA-256:   10739883288be9ea462c349231b9c7cd25f27571dc2011d948e12bd3a55c14b7
# Code AST SHA-256:   0569f40144586872f251e72bb0a7e432fe06b4ea9e24f135efb221253590f8d2
# Verified Classes:   TrustLaunderingError, ClearedField, ToolResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TrustLaunderingError(RuntimeError):
    """Raised when an artifact with mixed or unbound provenance is about to be
    consumed by a path that assumes ingestion-time sanitization still holds."""


@dataclass
class ClearedField:
    value: Any
    policy: str
    value_hash: str


@dataclass
class ToolResult:
    fields: dict[str, ClearedField] = field(default_factory=dict)
    untrusted_fields: dict[str, Any] = field(default_factory=dict)
    derived_from_model: bool = False


def _hash(v: Any) -> str:
    return hashlib.sha256(repr(v).encode()).hexdigest()


def consume(artifact: ToolResult, *, crosses_instance: bool, crosses_serialization: bool,
            crosses_model_rewrite: bool) -> dict[str, Any]:
    # Any uncleared sibling field is reachable if this path serializes generically.
    if artifact.untrusted_fields:
        raise TrustLaunderingError(
            f"record carries uncleared fields {sorted(artifact.untrusted_fields)}; "
            "generic serialization would leak them to the consumer"
        )
    # Field-scoped provenance must still match the current value.
    for name, cf in artifact.fields.items():
        if _hash(cf.value) != cf.value_hash:
            raise TrustLaunderingError(
                f"field {name!r} mutated after clearance; re-sanitize required"
            )
    # Model rewrites and cross-instance/serialization hops invalidate ingest trust.
    if artifact.derived_from_model or crosses_model_rewrite:
        raise TrustLaunderingError(
            "model-derived artifact cannot inherit ingest-time trust; re-scan required"
        )
    if crosses_instance or crosses_serialization:
        raise TrustLaunderingError(
            "artifact crosses an instance or serialization boundary; "
            "ingest-time clearance does not survive the hop"
        )
    return {name: cf.value for name, cf in artifact.fields.items()}


def handoff_to_subagent(artifact: ToolResult) -> dict[str, Any]:
    # Sub-agent is a different instance: this is a consumption boundary.
    return consume(
        artifact,
        crosses_instance=True,
        crosses_serialization=True,
        crosses_model_rewrite=False,
    )
