# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-induced-boundary-erosion-when-litmus-multi-turn-pressure-harnesses-coerce-the-grader-rather-than-the-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-induced-boundary-erosion-when-litmus-multi-turn-pressure-harnesses-coerce-the-grader-rather-than-the-agent.warrant.json
# Markdown SHA-256:   937beb7b07b1df83cd49a638f29a95221e963c81d03457a1a4f94c94177a415d
# Code AST SHA-256:   ec989f53e2cf47bfa1e66d64a343b8d894f753fe6c80a2b092e6011246dcaa1c
# Verified Classes:   ConfoundedLITMUSLabel
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConfoundedLITMUSLabel(RuntimeError):
    """Raised when a LITMUS harm label cannot be attributed to the agent."""
    pass


def attribute_harm_label(transcript: dict) -> str:
    """
    transcript = {
        "turns": [{"role": ..., "content": ..., "provenance": "agent"|"harness"|None}, ...],
        "label": "harmful"|"clean",
        "counterfactual_clean": bool | None,
    }
    Returns "agent_failure" | "harness_artifact" | "unresolved".
    """
    if transcript.get("label") != "harmful":
        return "clean"

    turns = transcript.get("turns", [])
    if not turns:
        raise ConfoundedLITMUSLabel("empty transcript cannot carry a harm label")

    if any(t.get("provenance") is None for t in turns):
        # No provenance: cannot attribute. Do not silently default to agent_failure.
        return "unresolved"

    harness_spans = [t for t in turns if t["provenance"] == "harness"]
    if not harness_spans:
        return "agent_failure"

    cf = transcript.get("counterfactual_clean")
    if cf is None:
        # Harness injected content but never ran counterfactual re-grade.
        raise ConfoundedLITMUSLabel(
            "harness-injected spans present but counterfactual_clean not computed; "
            "label is confounded and must not be published as agent behavior"
        )

    if cf:
        return "harness_artifact"
    return "agent_failure"
