# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quarantine-tainted-context-before-capability-downgrade-and-why-the-order-is-the-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quarantine-tainted-context-before-capability-downgrade-and-why-the-order-is-the-invariant.warrant.json
# Markdown SHA-256:   11ff3e886a090bd709d3936cfc7aec8a149a186e9ec9eeaa39988223421598cf
# Code AST SHA-256:   2b54f4c3cc07f48c3392da7d831551f1bf6b80584dbd35d82634aae282393b2f
# Verified Classes:   UnquarantinedDowngradeError, ContextState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnquarantinedDowngradeError(RuntimeError):
    """Raised when a capability downgrade is attempted against a context
    whose tainted span has not been verifiably excised."""
    pass


@dataclass
class ContextState:
    raw_spans: list[str]
    tainted_span_ids: set[str] = field(default_factory=set)
    quarantine_receipt: str | None = None

    def context_hash(self) -> str:
        h = hashlib.sha256()
        for s in self.raw_spans:
            h.update(s.encode("utf-8"))
        return h.hexdigest()


def commit_quarantine(ctx: ContextState) -> str:
    """Physically excise tainted spans, then seal the result with a receipt."""
    if not ctx.tainted_span_ids:
        raise UnquarantinedDowngradeError("no tainted spans registered; nothing to quarantine")
    ctx.raw_spans = [
        s for i, s in enumerate(ctx.raw_spans) if str(i) not in ctx.tainted_span_ids
    ]
    ctx.tainted_span_ids = set()
    ctx.quarantine_receipt = ctx.context_hash()
    return ctx.quarantine_receipt


def apply_capability_downgrade(
    ctx: ContextState,
    original_tools: set[str],
    flagged_tools: set[str],
) -> set[str]:
    """Compute and apply the downgrade ONLY against a quarantined context.

    The delta must be derived from post-quarantine context so that indirect
    substitution vectors (egress, delegation, write) are included, not just
    the directly-flagged tool.
    """
    if ctx.quarantine_receipt is None:
        raise UnquarantinedDowngradeError(
            "refusing downgrade: quarantine not committed; "
            "residual taint would survive the reduced tool surface"
        )
    if ctx.quarantine_receipt != ctx.context_hash():
        raise UnquarantinedDowngradeError(
            "refusing downgrade: context mutated after quarantine receipt; "
            "re-quarantine required"
        )

    # Post-quarantine delta: close direct vectors AND the substitution surface.
    substitution_surface = {"egress_webhook", "delegate_task", "write_file"}
    downgrade_set = flagged_tools | substitution_surface
    remaining = original_tools - downgrade_set
    if not remaining:
        raise UnquarantinedDowngradeError(
            "downgrade would leave zero capabilities; halt and rebuild from clean checkpoint"
        )
    return remaining


def enforce(original_tools: set[str], flagged_tools: set[str], ctx: ContextState) -> set[str]:
    """Ordered enforcement: quarantine must commit before downgrade applies."""
    try:
        commit_quarantine(ctx)
    except UnquarantinedDowngradeError:
        # Fail closed: do not downgrade over live taint.
        raise UnquarantinedDowngradeError(
            "quarantine could not commit; halting instance rather than "
            "issuing a downgrade the model can reason around"
        )
    return apply_capability_downgrade(ctx, original_tools, flagged_tools)
