# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-taint-cleared-mcp-output-as-still-unsafe-for-context-admission.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-taint-cleared-mcp-output-as-still-unsafe-for-context-admission.warrant.json
# Markdown SHA-256:   3f7dde68909f4c27b805d420656bbfb8ad70ce13d0894ab0928a265774d291e1
# Code AST SHA-256:   f8e2d75482090d104b153b406496577984ba87ed6ef90363c93c2ece26a0dabb
# Verified Classes:   TaintClearanceError, ClearanceRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintClearanceError(RuntimeError):
    """Raised when a cleared MCP output is not admissible to the target context."""
    pass


class ClearanceRecord:
    def __init__(self, output_id, derivation_chain, consumer_context, structural_only):
        self.output_id = output_id
        self.derivation_chain = derivation_chain  # list of (component, observed_by_sandbox)
        self.consumer_context = consumer_context
        self.structural_only = structural_only


def admit_to_context(record, target_context, cache_hit, cache_origin_context):
    # Condition 1: every derivation step must have been observed by the sandbox.
    unobserved = [step for step in record.derivation_chain if not step[1]]
    if unobserved:
        raise TaintClearanceError(
            f"output {record.output_id} derived by unobserved component(s) "
            f"{[s[0] for s in unobserved]}; structural clearance insufficient"
        )

    # Condition 2: clearance bound to consumer context.
    if record.consumer_context != target_context:
        raise TaintClearanceError(
            f"clearance for {record.output_id} bound to {record.consumer_context}, "
            f"not target {target_context}"
        )

    # Condition 4: cache hit across consumer boundaries is a clearance transfer.
    if cache_hit and cache_origin_context != target_context:
        raise TaintClearanceError(
            f"cache hit for {record.output_id} originates in {cache_origin_context}, "
            f"target {target_context}; re-quarantine required"
        )

    # Condition 3: structural-only clearance must be framed as untrusted content.
    if record.structural_only:
        return {"payload": record.output_id, "framing": "untrusted_content"}
    return {"payload": record.output_id, "framing": "trusted"}


def admit_or_quarantine(record, target_context, cache_hit, cache_origin_context):
    try:
        return admit_to_context(record, target_context, cache_hit, cache_origin_context)
    except TaintClearanceError:
        return {"payload": record.output_id, "framing": "quarantined"}
