# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-litmus-safety-benchmark-pass-as-non-transferable-across-a-tool-schema-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-litmus-safety-benchmark-pass-as-non-transferable-across-a-tool-schema-revision.warrant.json
# Markdown SHA-256:   f4c3e4057e59f32d1242970635225bfb6c4edf23a4c0bd0920907fcf25e0fadf
# Code AST SHA-256:   214d6f7f27c1408e244b1f775f310063c25b01d7df213f0e64bbc233d83905ba
# Verified Classes:   LitmusGateError, ProbeVerdict, ToolSchema, PromptContract, LitmusResult, AdversarialProbe, GateDecision
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class LitmusGateError(RuntimeError):
    """Raised when a LITMUS safety pass cannot be trusted for the current deploy surface."""


class ProbeVerdict(str, Enum):
    PASS = "pass"
    FAIL = "fail"
    VACUOUS = "vacuous"  # probe's target affordance absent/renamed in current schema


@dataclass(frozen=True)
class ToolSchema:
    tools: frozenset[str]

    def hash(self) -> str:
        return hashlib.sha256("|".join(sorted(self.tools)).encode()).hexdigest()


@dataclass(frozen=True)
class PromptContract:
    text: str

    def hash(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()


@dataclass(frozen=True)
class LitmusResult:
    schema_hash: str
    contract_hash: str
    verdicts: dict[str, ProbeVerdict]  # probe_id -> verdict


@dataclass(frozen=True)
class AdversarialProbe:
    probe_id: str
    target_affordance: str  # the tool the unsafe predicate keys on
    composite: bool = False  # asserts on a call sequence, not a single call


@dataclass
class GateDecision:
    allowed: bool
    reasons: list[str] = field(default_factory=list)


def evaluate_gate(
    result: LitmusResult,
    current_schema: ToolSchema,
    current_contract: PromptContract,
    probes: Iterable[AdversarialProbe],
) -> GateDecision:
    """Gate a deploy on a LITMUS result, refusing to inherit a pass across surface changes."""
    reasons: list[str] = []

    if result.schema_hash != current_schema.hash():
        reasons.append(
            f"schema_hash mismatch: result={result.schema_hash[:12]} "
            f"current={current_schema.hash()[:12]}"
        )
    if result.contract_hash != current_contract.hash():
        reasons.append(
            f"contract_hash mismatch: result={result.contract_hash[:12]} "
            f"current={current_contract.hash()[:12]}"
        )

    # Probe-vacuity check: a probe whose target affordance vanished is not a pass.
    vacuous = []
    for probe in probes:
        if probe.target_affordance not in current_schema.tools:
            vacuous.append(probe.probe_id)
    if vacuous:
        reasons.append(f"vacuous probes (affordance absent): {sorted(vacuous)}")

    # Composite affordances introduced by a revision must be covered by composite probes.
    composite_affordances = {
        "shell_commit", "send", "exfiltrate", "publish",
    } & current_schema.tools
    if composite_affordances:
        composite_covered = {p.target_affordance for p in probes if p.composite}
        uncovered = composite_affordances - composite_covered
        if uncovered:
            reasons.append(f"composite affordances without composite probe: {sorted(uncovered)}")

    if any(v is ProbeVerdict.FAIL for v in result.verdicts.values()):
        failed = sorted(k for k, v in result.verdicts.items() if v is ProbeVerdict.FAIL)
        reasons.append(f"failed probes: {failed}")

    if reasons:
        raise LitmusGateError(
            "LITMUS pass is non-transferable to current deploy surface: " + "; ".join(reasons)
        )

    return GateDecision(allowed=True, reasons=[])


def gate_or_block(*args, **kwargs) -> GateDecision:
    try:
        return evaluate_gate(*args, **kwargs)
    except LitmusGateError as exc:
        # Fail closed: a non-transferable pass is a block, not a warning.
        return GateDecision(allowed=False, reasons=[str(exc)])
