# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-invalidated-a-pending-tool-call-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-invalidated-a-pending-tool-call-contract.warrant.json
# Markdown SHA-256:   a7ad409c6478a7c56d017cdbf8055fe75eea108dd205052cfa1053c1a578fa95
# Code AST SHA-256:   20dc2cb9bc234c51ab7919b5f19ee1031ce5c2e407299eae89dc67949fa4863a
# Verified Classes:   CompactionContractViolation, ToolCallContract, CompactionController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class CompactionContractViolation(RuntimeError):
    """Raised when a compaction pass would cross an open tool-call contract,
    or when a post-compaction transcript contains an orphaned tool result."""
    pass


@dataclass(frozen=True)
class ToolCallContract:
    call_id: str
    tool_name: str
    canonical_args_hash: str
    schema_version: str
    expected_result_shape: str

    @staticmethod
    def from_call(call_id: str, tool_name: str, args: dict[str, Any],
                  schema_version: str, expected_result_shape: str) -> "ToolCallContract":
        canon = repr(sorted(args.items())).encode()
        return ToolCallContract(
            call_id=call_id,
            tool_name=tool_name,
            canonical_args_hash=hashlib.sha256(canon).hexdigest(),
            schema_version=schema_version,
            expected_result_shape=expected_result_shape,
        )


@dataclass
class CompactionController:
    pending_calls: dict[str, ToolCallContract] = field(default_factory=dict)
    max_deferral_ms: int = 30_000

    def register_call(self, contract: ToolCallContract) -> None:
        self.pending_calls[contract.call_id] = contract

    def resolve_call(self, call_id: str) -> None:
        self.pending_calls.pop(call_id, None)

    def assert_compaction_safe(self, oldest_pending_age_ms: int) -> None:
        """Fence: refuse to compact across an open contract unless the oldest
        pending call has exceeded its deferral budget, in which case the
        caller MUST switch to contract-preserving compaction."""
        if not self.pending_calls:
            return
        if oldest_pending_age_ms <= self.max_deferral_ms:
            raise CompactionContractViolation(
                f"compaction blocked: {len(self.pending_calls)} open tool-call "
                f"contract(s) in flight, oldest age {oldest_pending_age_ms}ms "
                f"<= deferral budget {self.max_deferral_ms}ms"
            )
        # Beyond budget: caller must inject contracts verbatim, not summarize.
        raise CompactionContractViolation(
            f"deferral budget exceeded with {len(self.pending_calls)} open "
            f"contract(s); switch to contract-preserving compaction and arm "
            f"cancellation timer for: {sorted(self.pending_calls)}"
        )

    def validate_post_compaction(self, window: list[dict[str, Any]]) -> None:
        """Every tool result in the active window must bind to a prior
        assistant tool_call id in the SAME window."""
        issued: set[str] = set()
        for msg in window:
            if msg.get("role") == "assistant":
                for tc in msg.get("tool_calls", []):
                    issued.add(tc["id"])
            elif msg.get("role") == "tool":
                tcid = msg.get("tool_call_id")
                if tcid not in issued:
                    raise CompactionContractViolation(
                        f"orphaned tool result in post-compaction window: "
                        f"tool_call_id={tcid!r} has no matching assistant "
                        f"tool_call in the current context"
                    )

    def inject_contract_block(self) -> dict[str, Any]:
        """Authoritative, non-narrative block to append after summarization."""
        return {
            "role": "system",
            "content": "PENDING_TOOL_CONTRACTS (authoritative; overrides any "
                       "prose in the summary): "
                       + repr([c.__dict__ for c in self.pending_calls.values()]),
        }
