# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-tainted-capability-grant-across-an-a2a-handoff-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-tainted-capability-grant-across-an-a2a-handoff-boundary.warrant.json
# Markdown SHA-256:   a7515cc98a17f33699d6435ffe9d12c5ccf73578b8b8b4884f956f414e6a75df
# Code AST SHA-256:   f456b42e628f679c7c9636354b2064175f56c74a3581498152cfef274e2fdc5d
# Verified Classes:   TaintLattice, TaintLaunderingError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import FrozenSet


class TaintLattice(IntEnum):
    CLEAN = 0
    INTERNAL = 1
    UNTRUSTED_EXTERNAL = 2
    SECRET = 3  # join with UNTRUSTED_EXTERNAL yields the top element below


TOP = 99


def join(a: int, b: int) -> int:
    if a == TOP or b == TOP:
        return TOP
    if {a, b} == {TaintLattice.UNTRUSTED_EXTERNAL, TaintLattice.SECRET}:
        return TOP  # secret-external mix is maximally confined
    return max(a, b)


class TaintLaunderingError(RuntimeError):
    """Raised when a delegated warrant drops or lowers inherited taint."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    taint: int
    parent_taint: int
    signature: str
    declassified_by: str | None = None


def verify_and_derive(
    w: Warrant,
    expected_subject: str,
    verifier_key_ok: bool,
) -> FrozenSet[str]:
    if not verifier_key_ok:
        raise TaintLaunderingError(f"warrant from {w.issuer} failed signature verification")
    if w.subject != expected_subject:
        raise TaintLaunderingError(
            f"warrant subject {w.subject} != receiving agent {expected_subject}"
        )
    # Invariant: taint is monotone across delegation unless explicitly declassified.
    if w.taint < w.parent_taint and w.declassified_by is None:
        raise TaintLaunderingError(
            f"warrant taint {w.taint} < parent taint {w.parent_taint} "
            f"with no declassifier identity"
        )
    if w.taint == TOP:
        # Top element: no capabilities derivable; must be handled by declassifier.
        return frozenset()
    return frozenset(w.scope)


def grant_derive(
    warrant: Warrant,
    verifier_key_ok: bool,
    local_taint: int,
    receiving_agent: str,
) -> FrozenSet[str]:
    """Total function of (warrant, joined taint). Fails closed if taint unknown."""
    if not isinstance(warrant.taint, int):
        raise TaintLaunderingError("warrant carries no signed taint field")
    joined = join(warrant.taint, local_taint)
    base = verify_and_derive(warrant, receiving_agent, verifier_key_ok)
    if joined >= TaintLattice.UNTRUSTED_EXTERNAL:
        # Confinement: untrusted-tainted input may only touch sandboxed VFS ops.
        return frozenset(c for c in base if c.startswith("vfs:"))
    return base
