# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-generated-adversarial-turn-as-a-validated-probe-rather-than-as-a-live-instruction-and-what-break.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-generated-adversarial-turn-as-a-validated-probe-rather-than-as-a-live-instruction-and-what-break.warrant.json
# Markdown SHA-256:   1e68430763ff5d57a8a64e16a7a010679dd3fe968ea7e71b5c23bedf23a2c4d9
# Code AST SHA-256:   08f4ad9093d7652c1c2cf4b084c784ab722fbd9611a5ede9c2d11c496b9f229c
# Verified Classes:   ProvenanceCollapseError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceCollapseError(RuntimeError):
    """Raised when an adversarial turn reaches the reasoning trace without verified provenance."""


PROBE = "PROBE"
PRINCIPAL = "PRINCIPAL"


def assemble_turn(raw_turn: dict, signature_verifier) -> dict:
    """
    Context-assembly boundary. Must run BEFORE the turn body is tokenized
    into the agent's reasoning trace. Returns a structured turn record with
    a verified provenance bit, or raises.
    """
    body = raw_turn.get("body")
    sidecar = raw_turn.get("provenance", {})
    sig = sidecar.get("signature")
    claimed = sidecar.get("kind")

    if body is None or sig is None or claimed not in (PROBE, PRINCIPAL):
        raise ProvenanceCollapseError(
            f"turn {raw_turn.get('id')!r} has no signature-bound provenance; "
            "refusing to assemble (content would enter reasoning trace unlabeled)"
        )

    # Signature MUST cover the body, not a sidecar field. A signature over
    # an empty/auxiliary payload is a provenance-collapse vector.
    if not signature_verifier.verify(body=body, signature=sig):
        raise ProvenanceCollapseError(
            f"turn {raw_turn.get('id')!r} signature does not bind to body; "
            "probe content is mutable and the measurement is invalid"
        )

    return {"provenance": claimed, "body": body, "id": raw_turn["id"]}


def dispatch(turn_record: dict, agent) -> None:
    """
    Route by verified provenance. PROBE turns are analyzed, never executed
    as principal instructions; PRINCIPAL turns execute under normal policy.
    """
    if turn_record["provenance"] == PROBE:
        agent.analyze_probe(turn_record["body"])  # compliance signal only
        return
    agent.execute_principal(turn_record["body"])


def run_scenario(turns: list[dict], verifier, agent) -> list[str]:
    trace = []
    for raw in turns:
        try:
            record = assemble_turn(raw, verifier)
        except ProvenanceCollapseError as exc:
            # Halt: a scenario that lost provenance is not a valid measurement,
            # and continuing would poison episodic memory with unlabeled probes.
            trace.append(f"HALT at turn {raw.get('id')!r}: {exc}")
            raise
        dispatch(record, agent)
        trace.append(f"turn {record['id']!r} -> {record['provenance']}")
    return trace
