# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-propagation-gap-at-the-tool-call-interception-boundary-when-arguments-are-reconstructed-rather-than-passed-by.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-propagation-gap-at-the-tool-call-interception-boundary-when-arguments-are-reconstructed-rather-than-passed-by.warrant.json
# Markdown SHA-256:   8d9fd1d93b37182babd07aaae1bec0e5955b7c46939bbb57a10d64af0e8d33f5
# Code AST SHA-256:   5d83243f76d3a1d16ccaad02d87baff0d9281e77ca1c9d8b1f3e64b92634d449
# Verified Classes:   TaintDecision, ProvenanceGapError, LaunderingSuspectedError, ProvenanceNode, ProvenanceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintDecision(Enum):
    ALLOW = "allow"
    DENY = "deny"
    DENY_UNKNOWN = "deny_unknown"
    DENY_SUSPECTED_LAUNDER = "deny_suspected_launder"


class ProvenanceGapError(RuntimeError):
    """Raised when a sink argument has no resolvable provenance node."""


class LaunderingSuspectedError(RuntimeError):
    """Raised when a reconstructed argument matches a known-tainted content hash."""


@dataclass(frozen=True)
class ProvenanceNode:
    label_set: frozenset[str]
    content_hash: str


@dataclass
class ProvenanceGraph:
    nodes: dict[str, ProvenanceNode] = field(default_factory=dict)
    tainted_hashes: set[str] = field(default_factory=set)

    def resolve(self, arg_id: str) -> ProvenanceNode | None:
        return self.nodes.get(arg_id)

    def lookup_hash(self, content_hash: str) -> ProvenanceNode | None:
        if content_hash in self.tainted_hashes:
            return ProvenanceNode(label_set=frozenset({"untrusted:external"}),
                                  content_hash=content_hash)
        return None


SINK_PARAMS: Mapping[str, frozenset[str]] = {
    "write_file": frozenset({"content"}),
    "send_email": frozenset({"body", "to"}),
    "execute_shell": frozenset({"cmd"}),
}


def content_hash(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def enforce_tool_call(
    graph: ProvenanceGraph,
    tool: str,
    args: Mapping[str, str],
    arg_ids: Mapping[str, str],
) -> TaintDecision:
    """Taint-aware PEP. Args are reconstructed values; arg_ids are the planner-side
    identifiers that *should* anchor them to graph nodes. Unknown ids are denied
    for sink parameters rather than falling through to allow."""
    sinks = SINK_PARAMS.get(tool, frozenset())
    for param, value in args.items():
        if param not in sinks:
            continue
        arg_id = arg_ids.get(param)
        node = graph.resolve(arg_id) if arg_id else None
        if node is None:
            by_hash = graph.lookup_hash(content_hash(value))
            if by_hash is not None:
                raise LaunderingSuspectedError(
                    f"tool={tool} param={param} matches known-tainted hash "
                    f"{by_hash.content_hash[:12]} but has no provenance node"
                )
            raise ProvenanceGapError(
                f"tool={tool} param={param} has no resolvable provenance node; "
                f"cannot certify clean for sink parameter"
            )
        if node.label_set:
            return TaintDecision.DENY
    return TaintDecision.ALLOW


def guarded_write(graph: ProvenanceGraph, args: Mapping[str, str],
                  arg_ids: Mapping[str, str]) -> TaintDecision:
    try:
        return enforce_tool_call(graph, "write_file", args, arg_ids)
    except ProvenanceGapError:
        # Unresolved provenance on a sink is a denial, and the denial is logged
        # as a provenance-gap event rather than silently allowed.
        return TaintDecision.DENY_UNKNOWN
    except LaunderingSuspectedError:
        return TaintDecision.DENY_SUSPECTED_LAUNDER
