# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-adversarial-skill-probe-passes-the-litmus-benchmark-but-the-skill-remains-live-in-the-deployed-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-adversarial-skill-probe-passes-the-litmus-benchmark-but-the-skill-remains-live-in-the-deployed-agent.warrant.json
# Markdown SHA-256:   3cfbbb0badd4fecddb3301681bd8c1d7691387443dfbc6ff0b602a24d2105d6a
# Code AST SHA-256:   0fdb35f056a9b53703f0849166fdfac13c513a2b560315d0265be83c39f53bdf
# Verified Classes:   BenchmarkCertificateError, Verdict, DerivationEdge, Skill, ProbeSet
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class BenchmarkCertificateError(RuntimeError):
    """Raised when a LITMUS PASS is about to be consumed as a containment
    certificate for a skill whose probe set is not derivation-closed."""


class Verdict(str, Enum):
    PASS = "PASS"
    SURFACE_ONLY = "SURFACE_ONLY"
    FAIL = "FAIL"


@dataclass(frozen=True)
class DerivationEdge:
    """One hop from a top-level skill parameter to a downstream parameter."""
    from_param: str
    to_param: str
    kind: str  # "subskill" | "retrieval" | "handoff" | "deserialize"


@dataclass
class Skill:
    name: str
    top_level_params: tuple[str, ...]
    derivation_edges: tuple[DerivationEdge, ...] = field(default_factory=tuple)

    def derivation_depth(self) -> int:
        """Longest chain from any top-level param to any terminal param."""
        if not self.derivation_edges:
            return 0
        # adjacency over params
        adj: dict[str, list[str]] = {}
        for e in self.derivation_edges:
            adj.setdefault(e.from_param, []).append(e.to_param)

        def longest(node: str, seen: frozenset[str]) -> int:
            if node in seen:
                raise BenchmarkCertificateError(
                    f"cycle in derivation graph at {node!r} for skill {self.name!r}"
                )
            nxt = adj.get(node, [])
            if not nxt:
                return 0
            return 1 + max(longest(n, seen | {node}) for n in nxt)

        return max(longest(p, frozenset()) for p in self.top_level_params)

    def terminal_params(self) -> set[str]:
        adj_sources = {e.from_param for e in self.derivation_edges}
        adj_targets = {e.to_param for e in self.derivation_edges}
        return adj_targets - adj_sources


@dataclass
class ProbeSet:
    """Adversarial probes generated by the LITMUS mutator."""
    skill_name: str
    probed_params: frozenset[str]  # params the mutator actually negated


def certify(skill: Skill, probes: ProbeSet) -> Verdict:
    """Emit a LITMUS verdict, refusing to certify depth>=1 skills whose
    probe set does not cover every terminal derivation parameter."""
    if probes.skill_name != skill.name:
        raise BenchmarkCertificateError(
            f"probe set for {probes.skill_name!r} cannot certify skill {skill.name!r}"
        )

    depth = skill.derivation_depth()
    if depth == 0:
        # probe mutates the same surface the skill consumes; closure holds.
        return Verdict.PASS

    terminals = skill.terminal_params()
    uncovered = terminals - set(probes.probed_params)
    if uncovered:
        # The probe generator only mutated top-level params; downstream
        # terminals are unprobed. A PASS here would be a false certificate.
        return Verdict.SURFACE_ONLY

    return Verdict.PASS


def apply_runtime_policy(skill: Skill, probes: ProbeSet, relax_guards: bool) -> str:
    """Runtime policy layer: only a derivation-closed PASS may relax guards."""
    verdict = certify(skill, probes)

    if relax_guards and verdict is not Verdict.PASS:
        raise BenchmarkCertificateError(
            f"refusing to relax runtime guards for skill {skill.name!r}: "
            f"verdict is {verdict.value}, not derivation-closed PASS "
            f"(depth={skill.derivation_depth()}, "
            f"uncovered terminals={sorted(skill.terminal_params() - set(probes.probed_params))})"
        )

    if verdict is Verdict.SURFACE_ONLY:
        return f"LOG_ONLY:{skill.name}"
    return f"TRUSTED:{skill.name}"


# --- reproduction of the observed failure ---

reconciliation = Skill(
    name="file-reconciliation",
    top_level_params=("dir", "source"),
    derivation_edges=(
        DerivationEdge("source", "manifest", "retrieval"),
        DerivationEdge("manifest", "endpoint", "subskill"),
    ),
)

# LITMUS mutator negated only the top-level params it modeled.
litmus_probes = ProbeSet(
    skill_name="file-reconciliation",
    probed_params=frozenset({"dir", "source"}),
)

# The benchmark reported PASS; the correct verdict is SURFACE_ONLY.
assert certify(reconciliation, litmus_probes) is Verdict.SURFACE_ONLY

# The observed incident: a SURFACE_ONLY verdict was consumed to relax guards.
try:
    apply_runtime_policy(reconciliation, litmus_probes, relax_guards=True)
except BenchmarkCertificateError as exc:
    print(f"guardrail held: {exc}")
else:
    raise BenchmarkCertificateError(
        "guardrail failed to hold: SURFACE_ONLY verdict relaxed runtime guards"
    )
