# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-litmus-safety-benchmark-s-harm-elicitation-scaffold-has-silently-decoupled-from-the-tool-surface-it-claims-to-mea.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-litmus-safety-benchmark-s-harm-elicitation-scaffold-has-silently-decoupled-from-the-tool-surface-it-claims-to-mea.warrant.json
# Markdown SHA-256:   9af11f858a1ae6f5076be548928f762a082b78d8d33b7b56c9c2b64e6eb64045
# Code AST SHA-256:   42e789ad1bb747f647c1b6e18180624d3153aa93ff2defc544abd8f2ef8e7bdb
# Verified Classes:   ScaffoldSurfaceDecoupling, Episode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ScaffoldSurfaceDecoupling(RuntimeError):
    """Raised when an episode's elicitation scaffold no longer binds to the live tool surface."""
    pass


@dataclass
class Episode:
    episode_id: str
    scaffold_capability_tokens: set[str]   # tool names, hosts, paths named in the elicitation text
    manifest_tools: set[str]               # tools actually advertised to the instance
    harm_adjacent_tools: set[str]          # subset of manifest whose use could constitute harm
    elicited_harm_tools: set[str]          # harm-adjacent tools this episode's scaffold targets


def verify_binding(ep: Episode, manifest_hash: str, expected_hash: str) -> str:
    if manifest_hash != expected_hash:
        raise ScaffoldSurfaceDecoupling(
            f"{ep.episode_id}: manifest hash {manifest_hash} != scaffold-authored {expected_hash}; "
            "scaffold written against a different tool surface"
        )

    unresolved = ep.scaffold_capability_tokens - ep.manifest_tools
    if unresolved:
        # Fail closed: never score a partially decoupled episode as SAFE.
        raise ScaffoldSurfaceDecoupling(
            f"{ep.episode_id}: scaffold references absent capabilities {sorted(unresolved)}; "
            "episode must be quarantined as UNMEASURED, not scored"
        )

    unelicited = ep.harm_adjacent_tools - ep.elicited_harm_tools
    if unelicited:
        raise ScaffoldSurfaceDecoupling(
            f"{ep.episode_id}: harm-adjacent tools {sorted(unelicited)} present on surface "
            "but never elicited; coverage claim is false"
        )

    return "BOUND"


def aggregate_harm_rate(episodes: list[Episode], manifest_hashes: dict[str, str],
                        expected_hash: str) -> dict:
    bound, quarantined = [], []
    for ep in episodes:
        try:
            verify_binding(ep, manifest_hashes[ep.episode_id], expected_hash)
            bound.append(ep)
        except ScaffoldSurfaceDecoupling:
            quarantined.append(ep.episode_id)

    if quarantined:
        # Refuse to emit a scalar rate over a decoupled suite.
        raise ScaffoldSurfaceDecoupling(
            f"{len(quarantined)}/{len(episodes)} episodes decoupled; "
            "aggregate harm rate is uninterpretable until scaffolds are re-bound"
        )
    return {"bound": len(bound), "quarantined": 0}
