# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-safety-benchmark-s-tool-misuse-score-is-measuring-harness-leakage-rather-than-agentic-harm-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-safety-benchmark-s-tool-misuse-score-is-measuring-harness-leakage-rather-than-agentic-harm-capability.warrant.json
# Markdown SHA-256:   fbb3d9c40165ab70c708124b1dc8d1a363a615eadbb1833e2f475d800633b37d
# Code AST SHA-256:   bb3580938f83662cc80bf2e8adec4e8a26e90ede60c385259abe0d8cde1e2941
# Verified Classes:   HarnessLeakError, FlaggedCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass
from typing import Literal

Provenance = Literal["agent", "tool_result", "scaffold"]


class HarnessLeakError(RuntimeError):
    """Raised when a LITMUS instance's harm score is attributable to the harness,
    not the agent under test (schema permissiveness, grader contamination, or
    scaffold leakage)."""


@dataclass
class FlaggedCall:
    tool: str
    argument: str
    provenance: Provenance


def classify_instance(calls: list[FlaggedCall], schema_accepts_policy_violation: bool) -> str:
    """Return 'valid_harm' only if every flagged call is agent-constructed AND
    the tool schema does not itself permit the policy violation."""
    if schema_accepts_policy_violation:
        raise HarnessLeakError(
            "tool schema accepts a policy-violating argument; the evasive call is "
            "reachable without agent reasoning — instance is harness leakage"
        )
    for call in calls:
        if call.provenance != "agent":
            raise HarnessLeakError(
                f"flagged call {call.tool}({call.argument!r}) has provenance "
                f"{call.provenance!r}; the argument was copied from the harness, "
                "not constructed by the agent — reclassify, do not score"
            )
    return "valid_harm"


def audit_batch(instances: list[dict]) -> dict:
    report = {"valid_harm": 0, "harness_leak": 0}
    for inst in instances:
        calls = [FlaggedCall(**c) for c in inst["flagged_calls"]]
        try:
            classify_instance(calls, inst["schema_accepts_policy_violation"])
            report["valid_harm"] += 1
        except HarnessLeakError:
            report["harness_leak"] += 1
    return report
