# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reallocates-its-context-budget-mid-turn-and-silently-evicts-the-tool-call-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reallocates-its-context-budget-mid-turn-and-silently-evicts-the-tool-call-contract.warrant.json
# Markdown SHA-256:   76e27a171a1cb11b1a39e8a97946447e6c5e7491e5975e487ebfa4a1250f2421
# Code AST SHA-256:   4d14464f06450e47cd58162aa461d4f05ade348bb2e7b0fd3e547ce0f92c2a39
# Verified Classes:   ToolContractViolation, ToolDefinition, ToolResult, EvictionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ToolContractViolation(RuntimeError):
    """Raised when a tool result is presented without its paired schema and no tombstone exists."""
    pass


@dataclass
class ToolDefinition:
    name: str
    token_cost: int
    parameters: dict


@dataclass
class ToolResult:
    tool_name: str
    token_cost: int
    step: int
    payload: dict


@dataclass
class EvictionLedger:
    evicted_definitions: dict = field(default_factory=dict)   # tool_name -> step evicted
    retained_results: dict = field(default_factory=dict)      # tool_name -> list[ToolResult]
    tombstones: dict = field(default_factory=dict)            # tool_name -> bool


def evict_definition(ledger: EvictionLedger, definition: ToolDefinition, step: int) -> None:
    """Evict a tool-definition block. Refuses if results survive without a tombstone."""
    surviving = ledger.retained_results.get(definition.name, [])
    if surviving and not ledger.tombstones.get(definition.name, False):
        raise ToolContractViolation(
            f"Cannot evict definition for '{definition.name}' at step {step}: "
            f"{len(surviving)} result(s) survive (steps "
            f"{[r.step for r in surviving]}) and no tombstone is set. "
            f"Evict results atomically or write a tombstone first."
        )
    ledger.evicted_definitions[definition.name] = step


def assemble_context(ledger: EvictionLedger, results: list[ToolResult]) -> list[dict]:
    """Assemble the model-visible context. Refuses orphaned results."""
    assembled = []
    for result in results:
        if result.tool_name in ledger.evicted_definitions:
            if not ledger.tombstones.get(result.tool_name, False):
                raise ToolContractViolation(
                    f"Result from '{result.tool_name}' (step {result.step}) is orphaned: "
                    f"definition evicted at step {ledger.evicted_definitions[result.tool_name]} "
                    f"with no tombstone. Model would confabulate the schema."
                )
            assembled.append({
                "type": "tombstone",
                "tool": result.tool_name,
                "note": "schema evicted; re-fetch before next call",
            })
        else:
            assembled.append({"type": "result", "tool": result.tool_name, "payload": result.payload})
    return assembled


def safe_evict_and_assemble(definition, results, step):
    ledger = EvictionLedger()
    ledger.retained_results[definition.name] = results
    # This will raise unless a tombstone is written first.
    evict_definition(ledger, definition, step)
    return assemble_context(ledger, results)
