# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-gate-desynchronization-when-a-capability-downgrade-silently-re-labels-a-tainted-tool-result-as-clean.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-gate-desynchronization-when-a-capability-downgrade-silently-re-labels-a-tainted-tool-result-as-clean.warrant.json
# Markdown SHA-256:   0861c6a817e8efb216e22557a78ea8b52d20314e7a3b85ea52f819aa75ac7223
# Code AST SHA-256:   5bb0a6f3595d11592a01f2b21da040306f68c11cb8ea3a69307ac353200f4d3b
# Verified Classes:   TaintDesyncError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintDesyncError(RuntimeError):
    """Raised when a capability downgrade would drop or launder taint labels
    on a value in flight, producing a clean-looking wrapper from a tainted one."""
    pass


def apply_downgrade(
    principal: str,
    pending_value: "ToolResult",
    new_capability: "Capability",
    declassification_rules: set[str],
) -> "ToolResult":
    """Apply a capability downgrade to a value in flight, atomically reconciling
    the taint plane with the capability plane.

    Invariant: taint_after must be a subset of taint_before, and any source
    class removed must be named in declassification_rules. A schema-changing
    downgrade re-wraps the value; the re-wrap MUST carry taint forward
    explicitly and MUST NOT rely on a default-clean constructor.
    """
    taint_before = frozenset(pending_value.taint_sources)

    if new_capability.output_schema != pending_value.schema:
        # Re-wrap under new schema. Taint is threaded through explicitly.
        re_wrapped = ToolResult(
            value=pending_value.value,
            schema=new_capability.output_schema,
            taint_sources=taint_before,  # explicit, never defaulted
            cap_ctx=new_capability.ctx,
        )
    else:
        re_wrapped = pending_value

    taint_after = frozenset(re_wrapped.taint_sources)
    laundered = taint_before - taint_after

    if laundered - declassification_rules:
        # Taint was dropped without a named declassification rule.
        raise TaintDesyncError(
            f"downgrade for {principal!r} laundered taint sources "
            f"{sorted(laundered - declassification_rules)}; "
            f"before={sorted(taint_before)} after={sorted(taint_after)} "
            f"schema={new_capability.output_schema!r}"
        )

    if not taint_after and taint_before:
        # Belt-and-suspenders: empty-after-from-nonempty is only legal if
        # every source was explicitly declassified.
        if taint_before - declassification_rules:
            raise TaintDesyncError(
                f"downgrade produced CLEAN from tainted value for {principal!r}"
            )

    commit_capability(principal, new_capability)
    return re_wrapped
