# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-tainted-context-allowlist-decision-be-re-evaluated-the-stale-derivation-boundary-in-tool-call-policy-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-tainted-context-allowlist-decision-be-re-evaluated-the-stale-derivation-boundary-in-tool-call-policy-enforcement.warrant.json
# Markdown SHA-256:   5daec19ef6fb1c9b0604f142a81fd9e530702db86d27bb5bcf893589ce4bb48c
# Code AST SHA-256:   bb2b437f12a61db8527ec2eda546baf74ceaa29ab21f307cdbab1940af60b3ab
# Verified Classes:   StaleAllowlistError, AllowlistDerivation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleAllowlistError(RuntimeError):
    """Raised when an enforced allowlist was derived from taint annotations
    that have since been mutated. The allowlist no longer summarizes the
    current taint state and must not be used for enforcement."""
    pass


class AllowlistDerivation:
    def __init__(self, permitted_tools, consumed_annotations, store_version):
        self.permitted_tools = frozenset(permitted_tools)
        self.consumed_annotations = frozenset(consumed_annotations)
        self.store_version = store_version


def enforce_tool_call(derivation, current_store_version, tool_name):
    # The derivation is valid only if every annotation it consumed is
    # unchanged. We approximate "unchanged" with a monotonic store version:
    # any mutation, including propagation-induced re-labeling, advances it.
    if derivation.store_version != current_store_version:
        raise StaleAllowlistError(
            f"allowlist derived at store version {derivation.store_version} "
            f"but current version is {current_store_version}; "
            f"consumed annotations {sorted(derivation.consumed_annotations)} "
            f"may have been mutated. Re-derive before enforcing {tool_name!r}."
        )
    if tool_name not in derivation.permitted_tools:
        raise PermissionError(
            f"tool {tool_name!r} not in allowlist "
            f"{sorted(derivation.permitted_tools)}"
        )
    return True


def derive_allowlist(taint_graph, store_version):
    # Walk the graph, collect labels, emit permitted tools and the exact
    # annotation identifiers consumed. The manifest is the load-bearing
    # artifact: without it, staleness is undetectable.
    consumed = set()
    permitted = {"read_file", "search"}
    for node in taint_graph.nodes():
        for label in node.labels:
            consumed.add(label.identifier)
            if label.kind == "pii":
                permitted.discard("send_email")
    return AllowlistDerivation(permitted, consumed, store_version)
