# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-mint-a-capability-token-mid-sandbox-the-taint-laundering-failure-at-the-token-refresh-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-mint-a-capability-token-mid-sandbox-the-taint-laundering-failure-at-the-token-refresh-boundary.warrant.json
# Markdown SHA-256:   b52f1a73c3a0a1b3cb0d6e89466db03523f1270f6aa5e6598d915c2fb7af2603
# Code AST SHA-256:   db5813cc72afab9f79cd6764094cb59ada73521e467dc4b63b7e77eac90934a3
# Verified Classes:   TaintLaunderingError, Capability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintLaunderingError(RuntimeError):
    """Raised when a capability re-mint would lower taint below the derived arguments."""
    pass

@dataclass(frozen=True)
class Capability:
    token_id: str
    scope: FrozenSet[str]
    taint: FrozenSet[str]          # provenance labels authorized under this token
    expires_at: float

def derive_taint(arguments: dict, retrievals: FrozenSet[str]) -> FrozenSet[str]:
    # Any argument sourced from a retrieval inherits that retrieval's taint.
    derived = set()
    for key, val in arguments.items():
        if isinstance(val, str) and val in retrievals:
            derived.add(f"src:{val}")
        if isinstance(val, str) and (".." in val or val.startswith("/etc")):
            derived.add("path:traversal")
    return frozenset(derived)

def refresh_capability(cap: Capability, now: float,
                       pending_tool: str, arguments: dict,
                       retrievals: FrozenSet[str],
                       normalize) -> Capability:
    if now >= cap.expires_at:
        raise TaintLaunderingError(f"token {cap.token_id} expired at {cap.expires_at}")
    norm_args = normalize(arguments)
    derived = derive_taint(norm_args, retrievals)
    # Invariant: taint must be monotone non-decreasing across refresh.
    if not derived.issubset(cap.taint):
        raise TaintLaunderingError(
            f"refresh of {cap.token_id} for tool {pending_tool} would lower taint: "
            f"derived={sorted(derived)} not subset of token taint={sorted(cap.taint)}"
        )
    return Capability(
        token_id=f"{cap.token_id}+r",
        scope=cap.scope,
        taint=cap.taint | derived,      # lattice join, never replacement
        expires_at=now + 90.0,
    )
