# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-launder-tainted-tool-output-through-a-clean-context-subcall-the-provenance-collapse-boundary-in-prompt-injection-tain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-launder-tainted-tool-output-through-a-clean-context-subcall-the-provenance-collapse-boundary-in-prompt-injection-tain.warrant.json
# Markdown SHA-256:   9190b6516034c5896a39d27c5ff00156bde8c7ca5e19383f744c430c9cfb35d7
# Code AST SHA-256:   26b5b5bffa0f1128e980488e6f85549155ed3ba2fa74831f287df8c7764355f5
# Verified Classes:   ProvenanceCollapseError, TaintLabel
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceCollapseError(RuntimeError):
    """Raised when a derivation's taint label is narrower than its causal input set."""


class TaintLabel:
    CLEAN = "CLEAN"
    UNTRUSTED = "UNTRUSTED"

    @staticmethod
    def join(labels):
        if TaintLabel.UNTRUSTED in labels:
            return TaintLabel.UNTRUSTED
        return TaintLabel.CLEAN


PROVENANCE_DESTROYING = {"summarize", "translate", "rewrite", "plan", "critique", "embed"}


def label_subcall_output(subcall_kind, input_handles, output_bytes, known_tainted_spans):
    """
    input_handles: list of (handle_id, taint_label) for every provenance handle
                   present in the subcall's context window at execution time.
    output_bytes: the subcall's emitted artifact.
    known_tainted_spans: byte spans known to be tainted (lexical check only).
    """
    if not input_handles:
        raise ProvenanceCollapseError(
            "subcall executed with no enumerable input handles; "
            "cannot compute causal taint join"
        )

    causal_join = TaintLabel.join([lbl for _, lbl in input_handles])

    lexical_hit = any(span in output_bytes for span in known_tainted_spans)

    if subcall_kind in PROVENANCE_DESTROYING:
        # Lossy derivation: lexical match is irrelevant. Taint is the batch join.
        if causal_join == TaintLabel.UNTRUSTED:
            return TaintLabel.UNTRUSTED
        return TaintLabel.CLEAN

    # Provenance-preserving derivation: per-item attribution admissible.
    if lexical_hit:
        return TaintLabel.UNTRUSTED
    return causal_join


def admit_to_trusted_context(artifact, label, declassification_ledger):
    if label == TaintLabel.CLEAN:
        entry = declassification_ledger.get(artifact.hash)
        if entry is None:
            raise ProvenanceCollapseError(
                f"artifact {artifact.hash[:12]} labeled CLEAN with no declassification "
                f"ledger entry; refusing admission to trusted context"
            )
        return True
    raise ProvenanceCollapseError(
        f"artifact {artifact.hash[:12]} is UNTRUSTED; "
        f"must route through declassification, not direct admission"
    )


def guard_side_effect_call(justifying_context, declassification_ledger):
    for artifact in justifying_context:
        if artifact.label == TaintLabel.CLEAN and artifact.hash not in declassification_ledger:
            raise ProvenanceCollapseError(
                f"side-effect call justified by CLEAN-by-default artifact "
                f"{artifact.hash[:12]}; unsound, refusing"
            )
    return True
