# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-delegation-from-laundering-data-across-residency-boundaries-when-sub-agents-re-derive-restricted-fields.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-delegation-from-laundering-data-across-residency-boundaries-when-sub-agents-re-derive-restricted-fields.warrant.json
# Markdown SHA-256:   91b52f88f037db77312a048327141ecdef6f3c6d2c351e03c988fdf764701375
# Code AST SHA-256:   c7c55753ab1c1b88cf76f2fbb96b39361891d70dbead85e7ba74fa629caf282c
# Verified Classes:   ResidencyLaunderingError, Field
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ResidencyLaunderingError(RuntimeError):
    """Raised when a delegated task result carries a value derivable from,
    or matching, a field the executor was never authorized to hold."""


@dataclass
class Field:
    name: str
    value: str
    classification: str          # e.g. "EU_ONLY", "EU_ONLY_DERIVABLE", "PUBLIC"
    provenance: tuple[str, ...] = field(default_factory=tuple)  # agent-authored fields must list inputs


RESTRICTED = "EU_ONLY"
ANONYMITY_K = 8  # require >= log2(8)=3 bits residual entropy in permitted set


def derivability_ok(permitted: Iterable[Field], restricted_residual_bits: float) -> bool:
    """Egress gate: reject if permitted set leaves too little entropy in restricted fields."""
    import math
    if restricted_residual_bits < math.log2(ANONYMITY_K):
        return False
    return all(f.classification != RESTRICTED for f in permitted)


def join_classification(inputs: Iterable[Field]) -> str:
    """Classification of a derived value = least upper bound of its provenance."""
    classes = {f.classification for f in inputs}
    if RESTRICTED in classes or f"{RESTRICTED}_DERIVABLE" in classes:
        return RESTRICTED
    return "PUBLIC"


def reclassify_return(returned: Iterable[Field], restricted_values: set[str]) -> None:
    """Return-leg check: trust no executor tag; match strings and joins ourselves."""
    for f in returned:
        if f.value in restricted_values:
            raise ResidencyLaunderingError(
                f"returned field {f.name!r} matches restricted value held by delegator"
            )
        if not f.provenance and f.classification == "PUBLIC":
            raise ResidencyLaunderingError(
                f"agent-authored field {f.name!r} has no provenance; cannot verify classification"
            )
        if f.provenance:
            # reconstruct inputs from the delegator's own record of what it sent
            joined = join_classification(_lookup(f.provenance))
            if joined == RESTRICTED and f.classification != RESTRICTED:
                raise ResidencyLaunderingError(
                    f"field {f.name!r} derived from restricted inputs but tagged {f.classification}"
                )


def delegate(permitted: list[Field], residual_bits: float,
             returned: list[Field], restricted_values: set[str]) -> None:
    if not derivability_ok(permitted, residual_bits):
        raise ResidencyLaunderingError(
            "permitted field set too informative; delegation would permit reconstruction"
        )
    reclassify_return(returned, restricted_values)


def _lookup(provenance: tuple[str, ...]) -> list[Field]:
    # delegator's own record of fields it transmitted
    return [Field(n, "", RESTRICTED if n == "postal_prefix" else "PUBLIC") for n in provenance]
