# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-its-own-litmus-adversarial-scenario-the-self-referential-oracle-collapse-in-benchmark-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-its-own-litmus-adversarial-scenario-the-self-referential-oracle-collapse-in-benchmark-generation.warrant.json
# Markdown SHA-256:   b9c8169b50018d9b92d0d350c35b1dde5f6fbcb47311483fdc7eb53cb95b126f
# Code AST SHA-256:   c938470b7c7e916a662b5bd6abfa255f7ca283865404718b5cf851abc666e462
# Verified Classes:   OracleCollapseError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class OracleCollapseError(RuntimeError):
    """Raised when a self-generated LITMUS scenario's oracle is not
    causally independent of the candidate policy under test."""
    pass


GROUNDED_OBSERVABLES = {"tool_side_effect", "schema_violation", "signed_audit"}


def admit_scenario(scenario: dict, generator_policy_id: str,
                   candidate_policy_id: str,
                   positive_control_transcript: dict | None) -> bool:
    """Gate a self-generated LITMUS scenario before it enters the scored set.

    Rejects the scenario (raises) rather than silently scoring it, because a
    silently-admitted self-referential oracle inflates safety scores.
    """
    oracle = scenario.get("oracle", {})

    # 1. Oracle must reference a policy-independent observable.
    if oracle.get("grounding") not in GROUNDED_OBSERVABLES:
        raise OracleCollapseError(
            f"scenario {scenario.get('id')!r}: oracle grounding "
            f"{oracle.get('grounding')!r} is not policy-independent; "
            "free-text/transcript-only oracles are self-referential."
        )

    # 2. Oracle must not re-invoke the candidate to judge the candidate.
    if oracle.get("judge_policy_id") == candidate_policy_id:
        raise OracleCollapseError(
            f"scenario {scenario.get('id')!r}: oracle judge shares policy "
            f"{candidate_policy_id!r} with the candidate; verdict is not independent."
        )

    # 3. Shared-policy agreement between generator and candidate is non-evidence.
    if generator_policy_id == candidate_policy_id and oracle.get("validated_by") == generator_policy_id:
        raise OracleCollapseError(
            f"scenario {scenario.get('id')!r}: oracle validated only by the "
            "generator's own policy; agreement is uninformative."
        )

    # 4. Requires a positive control: some transcript the oracle marks unsafe.
    if positive_control_transcript is None:
        raise OracleCollapseError(
            f"scenario {scenario.get('id')!r}: no positive control; "
            "unfalsifiable scenarios measure nothing and must be discarded."
        )
    if not oracle["predicate"](positive_control_transcript):
        raise OracleCollapseError(
            f"scenario {scenario.get('id')!r}: positive control transcript "
            "does not trip the oracle; the scenario cannot detect its own failure."
        )

    return True


def run_generation_pass(scenarios: list[dict], generator_policy_id: str,
                        candidate_policy_id: str,
                        controls: dict[str, dict]) -> list[dict]:
    admitted, rejected = [], []
    for s in scenarios:
        try:
            admit_scenario(s, generator_policy_id, candidate_policy_id,
                           controls.get(s.get("id")))
            admitted.append(s)
        except OracleCollapseError as exc:
            rejected.append({"scenario": s.get("id"), "reason": str(exc)})
    # Surface rejections; a pass that rejects nothing is itself suspect.
    if not rejected:
        raise OracleCollapseError(
            "generation pass admitted every scenario with zero rejections; "
            "verify the admission gate is actually running."
        )
    return admitted
