# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drift-from-its-declared-skill-manifest-after-a-red-team-tool-hijack-probe-and-silently-retain-a-stale-tool-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drift-from-its-declared-skill-manifest-after-a-red-team-tool-hijack-probe-and-silently-retain-a-stale-tool-binding.warrant.json
# Markdown SHA-256:   7cc2aaaf69ec58bc0f237e1b2ef77695423e8e0f03980d3c472fdbb0e15372f5
# Code AST SHA-256:   4c9571b5508673850b356c62bbaaafc059183d10c8e762a881489bd92301c5b1
# Verified Classes:   BindingContaminationError, Instance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Dict


class BindingContaminationError(RuntimeError):
    """Raised when the live tool binding table diverges from the declared manifest
    at probe entry, indicating residual state from a prior probe."""
    pass


@dataclass
class Instance:
    declared_manifest: Dict[str, str]          # tool_name -> expected endpoint/skill id
    live_bindings: Dict[str, str] = field(default_factory=dict)


def assert_binding_isolation(instance: Instance, probe_id: str) -> None:
    """Fail closed if the live binding table does not match the declared manifest.

    A probe that runs against bindings it did not establish is not a probe of its
    own scenario; its result must not be attributed to that scenario.
    """
    for tool, expected in instance.declared_manifest.items():
        actual = instance.live_bindings.get(tool)
        if actual != expected:
            raise BindingContaminationError(
                f"probe {probe_id!r}: live binding for tool {tool!r} is {actual!r}, "
                f"declared manifest requires {expected!r}; residual hijack binding "
                f"from a prior probe is present. Refusing to run probe."
            )
    extra = set(instance.live_bindings) - set(instance.declared_manifest)
    if extra:
        raise BindingContaminationError(
            f"probe {probe_id!r}: undeclared tools present in live bindings: "
            f"{sorted(extra)}; manifest does not authorize them."
        )


def run_probe(instance: Instance, probe_id: str, scenario: Callable[[Instance], None]) -> None:
    assert_binding_isolation(instance, probe_id)
    scenario(instance)
    # Post-probe: restore declared manifest so the next probe starts clean,
    # but record any residual mutation as a persistence finding first.
    residual = {
        t: v for t, v in instance.live_bindings.items()
        if instance.declared_manifest.get(t) != v
    }
    if residual:
        # Persistence-of-hijack is a finding, not a silent inheritance.
        record_finding(probe_id, "residual_binding", residual)
        instance.live_bindings = dict(instance.declared_manifest)


def record_finding(probe_id: str, kind: str, detail: dict) -> None:
    # Emit to the harness finding log; kept minimal here.
    print(f"[finding] probe={probe_id} kind={kind} detail={detail}")
