# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-passes-litmus-at-turn-n-and-the-harness-keeps-its-verdict-cached-across-a-context-window-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-passes-litmus-at-turn-n-and-the-harness-keeps-its-verdict-cached-across-a-context-window-compaction.warrant.json
# Markdown SHA-256:   cdd6a572bfdf34fa09099f1e71293037037132c0e2882a020ee2e446864be761
# Code AST SHA-256:   e59e81c9f1837d2fdfc0b86d6d2df67097de6b3f240bfedbff1af4f70a814f14
# Verified Classes:   StaleVerdictError, ConformanceLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Literal

Verdict = Literal["PASS", "FAIL", "STALE"]

SAFETY_CRITICAL_SPANS = ("system_prompt", "guard_instructions", "tool_permissions")
RISKY_CAPABILITIES = frozenset({"write_file", "network_egress", "credential_access", "subprocess"})


class StaleVerdictError(RuntimeError):
    """Raised when a guard consumes a LITMUS verdict whose policy slice no longer exists."""


@dataclass
class ConformanceLedger:
    # keyed on (instance_id, policy_digest) -- NOT on instance_id alone
    _entries: dict[tuple[str, str], Verdict] = field(default_factory=dict)

    def record(self, instance_id: str, policy_digest: str, verdict: Verdict) -> None:
        self._entries[(instance_id, policy_digest)] = verdict

    def lookup(self, instance_id: str, policy_digest: str) -> Verdict:
        return self._entries.get((instance_id, policy_digest), "STALE")


def effective_policy_digest(active_context: dict) -> str:
    """Digest of the policy the model will *actually* condition on.

    Reconstructed from the active context, not from the declared config store.
    A summarizer that paraphrases a safety instruction changes this digest.
    """
    critical = {
        span: active_context.get(span, "")
        for span in SAFETY_CRITICAL_SPANS
    }
    canonical = json.dumps(critical, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def guard_tool_call(
    instance_id: str,
    active_context: dict,
    capability: str,
    ledger: ConformanceLedger,
) -> Verdict:
    """Pre-tool-call guard. Fails closed on STALE for risky capabilities."""
    digest = effective_policy_digest(active_context)
    verdict = ledger.lookup(instance_id, digest)

    if verdict == "FAIL":
        raise StaleVerdictError(
            f"instance {instance_id}: cached FAIL verdict; tool call denied "
            f"(capability={capability})"
        )

    if verdict == "STALE":
        if capability in RISKY_CAPABILITIES:
            # Fail closed: revalidation must complete before the call proceeds.
            raise StaleVerdictError(
                f"instance {instance_id}: policy_digest={digest[:12]} has no valid "
                f"LITMUS verdict (compaction or resume destroyed the certified slice); "
                f"capability={capability} is in risk surface -- revalidate before retry"
            )
        # Read-only capability covered by the original probe set: defer revalidation.
        return "STALE"

    return verdict
