# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-an-mcp-tool-result-re-entry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-an-mcp-tool-result-re-entry-boundary.warrant.json
# Markdown SHA-256:   c2215d01830d23285c4adcc7f9e4266ea8966823e474c0519790bda631dc6dd2
# Code AST SHA-256:   2a9dfecbdd5cfd288a57fe46cecf994cccf606042afdfbae214e9d6c9bea7505
# Verified Classes:   TaintContinuityError, Provenance, TaintedValue, CapabilityScope
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintContinuityError(RuntimeError):
    """Raised when a tainted argument crosses into a capability scope it cannot satisfy."""
    pass


@dataclass(frozen=True)
class Provenance:
    origin: str
    integrity: str  # "low" | "high"
    ancestry: tuple[str, ...] = ()

    def ancestry_hash(self) -> str:
        h = hashlib.sha256()
        for step in self.ancestry:
            h.update(step.encode())
        h.update(self.origin.encode())
        h.update(self.integrity.encode())
        return h.hexdigest()


@dataclass
class TaintedValue:
    value: Any
    provenance: Provenance


@dataclass
class CapabilityScope:
    name: str
    min_integrity: str


def derive_argument(arg: Any, callee_scope: CapabilityScope) -> dict:
    """Serialize an argument for an outbound MCP call, enforcing taint continuity."""
    if not isinstance(arg, TaintedValue):
        return {"value": arg}

    effective_integrity = arg.provenance.integrity
    if effective_integrity == "low" and callee_scope.min_integrity == "high":
        raise TaintContinuityError(
            f"taint continuity violated: argument from origin "
            f"{arg.provenance.origin!r} (integrity={effective_integrity}) "
            f"cannot enter scope {callee_scope.name!r} "
            f"(min_integrity={callee_scope.min_integrity}); "
            f"ancestry_hash={arg.provenance.ancestry_hash()}"
        )

    return {
        "value": arg.value,
        "_provenance": {
            "origin": arg.provenance.origin,
            "integrity": effective_integrity,
            "ancestry_hash": arg.provenance.ancestry_hash(),
        },
    }


def execute_hop(
    inbound: TaintedValue,
    callee_scope: CapabilityScope,
    transform: str,
) -> TaintedValue:
    """Simulate a hop: serialize, dispatch, re-label result with extended ancestry."""
    payload = derive_argument(inbound, callee_scope)
    # Broker would parse payload["_provenance"] here; assume it approves.
    new_prov = Provenance(
        origin=callee_scope.name,
        integrity="high" if callee_scope.min_integrity == "high" else "low",
        ancestry=inbound.provenance.ancestry + (transform,),
    )
    return TaintedValue(value=payload["value"], provenance=new_prov)


if __name__ == "__main__":
    untrusted = TaintedValue(
        value="/etc/agent/state.json",
        provenance=Provenance(origin="untrusted_endpoint", integrity="low"),
    )
    write_scope = CapabilityScope(name="fs:write", min_integrity="high")
    try:
        execute_hop(untrusted, write_scope, transform="path_arg")
    except TaintContinuityError as e:
        print(f"BLOCKED: {e}")
