# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-harness-side-contamination-when-the-litmus-canary-tool-s-side-effect-mutates-the-fixture-the-next-probe-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-harness-side-contamination-when-the-litmus-canary-tool-s-side-effect-mutates-the-fixture-the-next-probe-depends-on.warrant.json
# Markdown SHA-256:   04ef4486613404627b85536492c54b271378662430da9cfbbf7ffcb79bb28e4d
# Code AST SHA-256:   d917066bdea89fb673c407e5f3a0c917851090e3b91bf287cce0e6097d675df2
# Verified Classes:   FixtureDriftError, FixtureLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import os
from dataclasses import dataclass, field


class FixtureDriftError(RuntimeError):
    """Raised when a permitted probe tool mutated a fixture a later probe reads."""

    def __init__(self, path: str, before: str, after: str, tool_call: str):
        self.path = path
        self.before = before
        self.after = after
        self.tool_call = tool_call
        super().__init__(
            f"fixture drift at {path!r} caused by {tool_call!r}: "
            f"{before[:12]} -> {after[:12]}"
        )


@dataclass
class FixtureLedger:
    provisioned: dict[str, str] = field(default_factory=dict)
    guarded_paths: set[str] = field(default_factory=set)

    def provision(self, root: str, guarded: set[str]) -> None:
        for rel in guarded:
            canonical = os.path.realpath(os.path.join(root, rel))
            self.guarded_paths.add(canonical)
            self.provisioned[canonical] = self._hash(canonical)

    @staticmethod
    def _hash(path: str) -> str:
        try:
            with open(path, "rb") as fh:
                return hashlib.sha256(fh.read()).hexdigest()
        except FileNotFoundError:
            return "<absent>"

    def verify_after_call(self, tool_call: str) -> None:
        for canonical in self.guarded_paths:
            current = self._hash(canonical)
            expected = self.provisioned[canonical]
            if current != expected:
                raise FixtureDriftError(
                    path=canonical,
                    before=expected,
                    after=current,
                    tool_call=tool_call,
                )


def run_probe(ledger: FixtureLedger, tool_call: str, invoke) -> object:
    result = invoke()
    # The check must run on the canonicalized path set, not the literal
    # path the agent passed, or the symlink case slips through.
    ledger.verify_after_call(tool_call)
    return result
