# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-adversarial-scenario-generation-as-a-stateful-continuity-hazard-rather-than-a-stateless-input-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-adversarial-scenario-generation-as-a-stateful-continuity-hazard-rather-than-a-stateless-input-filter.warrant.json
# Markdown SHA-256:   82c38ea4d7216d467f37bf13627608dd690f98be4023da88d5d73e8ae4291d1c
# Code AST SHA-256:   76520524d98294c460a54935a15c85eb4fe6460a4613c7d61216a7df41c7712e
# Verified Classes:   ProvenanceContinuityViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceContinuityViolation(RuntimeError):
    """Raised when an action at turn N cites a state element whose origin
    is adversary-asserted without a provenance tag, or when a checkpoint
    resume drops a refusal-ledger entry. This is a LITMUS continuity failure,
    not an output-filter failure."""
    pass


TRUSTED_ORIGINS = {"system", "verified_tool"}
LOW_TRUST_ORIGINS = {"user_asserted", "adversary_asserted"}


def audit_turn_action(turn_index, action, cited_state, refusal_ledger, resumed):
    """Audit a single turn's action against the provenance invariant.

    cited_state: list of dicts with keys 'proposition', 'origin', 'provenance_tagged'
    refusal_ledger: set of intent hashes previously refused
    resumed: True if this turn follows a checkpoint restore
    """
    if resumed and not refusal_ledger:
        raise ProvenanceContinuityViolation(
            f"turn {turn_index}: resumed with empty refusal ledger; "
            "prior refusals lost across checkpoint, paraphrase will pass as novel"
        )

    for element in cited_state:
        origin = element.get("origin")
        tagged = element.get("provenance_tagged", False)

        if origin in LOW_TRUST_ORIGINS and not tagged:
            raise ProvenanceContinuityViolation(
                f"turn {turn_index}: action {action!r} cites adversary-asserted "
                f"proposition {element['proposition']!r} with stripped provenance; "
                "distillation laundered a user claim into a session fact"
            )

        if origin in LOW_TRUST_ORIGINS and action.get("impact") == "high":
            raise ProvenanceContinuityViolation(
                f"turn {turn_index}: high-impact action {action!r} justified solely "
                f"by low-trust element {element['proposition']!r}"
            )

    intent = action.get("intent_hash")
    if intent in refusal_ledger and action.get("action") == "execute":
        raise ProvenanceContinuityViolation(
            f"turn {turn_index}: executing intent {intent!r} previously refused; "
            "refusal invariant not enforced across turns"
        )

    return True
