# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-propagation-false-positive-is-forcing-premature-capability-downgrade-in-a-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-propagation-false-positive-is-forcing-premature-capability-downgrade-in-a-tool-sandbox.warrant.json
# Markdown SHA-256:   5fbb16da7a72e7d75ef331c1d64ae13aeb821c27ee80c733fbca536984c89b09
# Code AST SHA-256:   ebce26bc5be85fdd1f598f11e6f56d2e4363c265af086ea08917843f6801c01a
# Verified Classes:   TaintDowngradeFalsePositive, TaintSource, PendingCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintDowngradeFalsePositive(RuntimeError):
    """Raised when a capability downgrade is triggered by taint presence
    rather than by observed influence on a pending tool call."""
    pass


class TaintSource:
    def __init__(self, span_id: str, weight: float, referenced_turns: int = 1):
        self.span_id = span_id
        self.weight = weight
        self.referenced_turns = referenced_turns


class PendingCall:
    def __init__(self, call_id: str, tool: str, args: dict, influenced_by: set[str]):
        self.call_id = call_id
        self.tool = tool
        self.args = args
        self.influenced_by = influenced_by  # span_ids whose content shaped args


DOWNGRADE_THRESHOLD = 0.85
INFLUENCE_EPSILON = 0.0


def evaluate_downgrade(
    taint_sources: list[TaintSource],
    pending_calls: list[PendingCall],
) -> dict[str, str]:
    """
    Returns a mapping of call_id -> 'downgrade' | 'allow'.
    Raises TaintDowngradeFalsePositive if the aggregate-score path would
    have downgraded globally without any observed influence.
    """
    # Correct aggregation: max over distinct sources, NOT sum over references.
    max_suspicion = max((s.weight for s in taint_sources), default=0.0)
    over_threshold = max_suspicion >= DOWNGRADE_THRESHOLD

    # Influence check: does any pending call's args derive from a tainted span?
    influenced_calls = {
        c.call_id
        for c in pending_calls
        if any(src.span_id in c.influenced_by for src in taint_sources)
    }

    if over_threshold and not influenced_calls:
        # This is the false-positive boundary: suspicion fired on presence alone.
        # A naive runtime would issue a global capability revocation here.
        raise TaintDowngradeFalsePositive(
            f"Suspicion {max_suspicion:.2f} >= {DOWNGRADE_THRESHOLD} but no pending "
            f"call is influenced by any tainted span; global downgrade would be "
            f"a provenance-only false positive. Sources: "
            f"{[s.span_id for s in taint_sources]}"
        )

    decisions: dict[str, str] = {}
    for call in pending_calls:
        if over_threshold and call.call_id in influenced_calls:
            decisions[call.call_id] = "downgrade"  # scoped to this call only
        else:
            decisions[call.call_id] = "allow"
    return decisions


def apply_downgrade(decisions: dict[str, str], call: PendingCall) -> None:
    if decisions.get(call.call_id) == "downgrade":
        # Scoped revocation: only this call's capability set, never the session's.
        raise TaintDowngradeFalsePositive(
            f"Call {call.call_id} ({call.tool}) downgraded: arguments influenced by "
            f"tainted span(s) {sorted(call.influenced_by)}. Re-plan required; "
            f"do not retry with the same arguments."
        )
