# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-litmus-adversarial-suites-yet-fail-the-same-attack-in-production-refusal-scope-collapse-under-suite-local-context-framing.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-litmus-adversarial-suites-yet-fail-the-same-attack-in-production-refusal-scope-collapse-under-suite-local-context-framing.warrant.json
# Markdown SHA-256:   5a59e6de8477623499c2f494f1c038639b2dcf0eb54f308ff36c987b95e58104
# Code AST SHA-256:   544679bd8336354216cebec3ee0f1265d9eb3702d8e901a04eb3da98f6aaf680
# Verified Classes:   RefusalScopeCollapseError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RefusalScopeCollapseError(RuntimeError):
    """Raised when an instruction-bearing span is executed without
    provenance re-classification at a channel boundary."""
    pass


TRUSTED_CHANNELS = {"user_turn"}


def admit_span(span: dict, parent_task_committed: bool) -> dict:
    """Gate an instruction-bearing span before it can influence the plan.

    The invariant: provenance classification must not be inferable from
    channel alone. A tool result is data; any imperative or procedural
    content inside it must be re-surfaced as a candidate instruction.
    """
    channel = span.get("channel")
    content = span.get("content", "")
    has_instruction_surface = _looks_instructional(content)

    if channel in TRUSTED_CHANNELS:
        return {"admitted": True, "as": "instruction", "span": span}

    # Untrusted channel carrying instruction-shaped content.
    if has_instruction_surface:
        if parent_task_committed:
            # This is the collapse condition: task-commitment anchoring
            # makes the instance treat the payload as in-scope data.
            raise RefusalScopeCollapseError(
                f"instruction-bearing span on untrusted channel "
                f"'{channel}' under committed parent task; "
                f"refusal scope would collapse. Re-classify explicitly."
            )
        return {"admitted": False, "as": "quarantined", "span": span}

    return {"admitted": True, "as": "data", "span": span}


def _looks_instructional(content: str) -> bool:
    markers = ("must", "should", "follow", "procedure", "execute", "now")
    lowered = content.lower()
    return any(m in lowered for m in markers)
