# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-escalation-when-a-provenance-label-survives-tool-output-but-is-silently-downgraded-by-memory-write-normalization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-escalation-when-a-provenance-label-survives-tool-output-but-is-silently-downgraded-by-memory-write-normalization.warrant.json
# Markdown SHA-256:   2c0f3edea680beaa4eb07f82ee467e318973ad520f6f82bd1b0162006435268d
# Code AST SHA-256:   595b854c0ac62a236ddd1dcc91dd3620d19fc41d8748fe38cf9a5f3444f7ac13
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a retrieved segment's stored taint label is inconsistent
    with its origin chain, indicating a trust-elevating transform occurred."""


def check_segment_consistency(segment: dict) -> None:
    """
    segment = {
        "content": str,
        "origin_chain": list[str],   # e.g. ["agent", "external:web", "agent"]
        "stored_taint": str,         # "clean" | "untrusted"
        "author": str,
    }
    Enforces: a segment whose origin chain contains any external hop
    cannot carry stored_taint == "clean". Violation => quarantine.
    """
    chain = segment.get("origin_chain", [])
    stored = segment.get("stored_taint")
    has_external = any(hop.startswith("external:") for hop in chain)

    if has_external and stored == "clean":
        raise ProvenanceLaunderingError(
            f"Taint escalation: segment with external origin chain {chain} "
            f"carries stored_taint='clean'. Probable memory-write "
            f"normalization dropped the sidecar. Quarantine node."
        )

    if stored not in ("clean", "untrusted"):
        raise ProvenanceLaunderingError(
            f"Unrecognized taint label {stored!r}; refusing to trust it."
        )


def write_with_taint_preservation(node: dict, target_schema: set[str]) -> dict:
    """
    Fail-closed write path. If the target memory schema cannot represent
    the taint sidecar, refuse the write rather than silently downgrading.
    """
    required_keys = {"content", "origin_chain", "stored_taint", "author"}
    missing = required_keys - target_schema
    if missing:
        raise ProvenanceLaunderingError(
            f"Target schema {sorted(target_schema)} cannot represent "
            f"required provenance keys {sorted(missing)}. "
            f"Refusing write: silent taint downgrade would occur."
        )
    # Preserve origin chain; never re-stamp author to the writer.
    return {
        "content": node["content"],
        "origin_chain": list(node["origin_chain"]) + ["memory"],
        "stored_taint": node["stored_taint"],
        "author": node["author"],
    }


def grant_instruction_authority(segment: dict) -> bool:
    """
    Instruction authority requires full-internal origin AND clean taint.
    Re-derives from origin chain; does not trust stored label alone.
    """
    check_segment_consistency(segment)
    chain = segment["origin_chain"]
    fully_internal = all(not hop.startswith("external:") for hop in chain)
    return fully_internal and segment["stored_taint"] == "clean"
