# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-priority-inheritance-failure-in-hierarchical-planner-executor-context-budgets.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-priority-inheritance-failure-in-hierarchical-planner-executor-context-budgets.warrant.json
# Markdown SHA-256:   ff6e71704654ce9fb242edaaa655cf48ad4d6f0a2409277eefad9902206dcc8c
# Code AST SHA-256:   f10bd9bf12a542c76e02d09dafb6cbdad33a7a518b0cc50e94fc94bd772e03c8
# Verified Classes:   PriorityInheritanceViolation, CriticalInstruction, ToolResult, SatisfactionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PriorityInheritanceViolation(RuntimeError):
    """Raised when a critical instruction is evicted without a discharging tool result."""


@dataclass
class CriticalInstruction:
    instruction_id: str
    text: str
    postcondition: Optional[str]  # evaluable predicate over tool results; None => planning defect
    pinned: bool = True
    discharged_by: Optional[str] = None  # tool_result_id that satisfied postcondition


@dataclass
class ToolResult:
    tool_result_id: str
    tool_name: str
    ok: bool
    structured: dict = field(default_factory=dict)


class SatisfactionLedger:
    """Harness-level checker. Eviction MUST route through try_evict."""

    def __init__(self, min_progress_budget: int):
        self.instructions: dict[str, CriticalInstruction] = {}
        self.min_progress_budget = min_progress_budget
        self.tool_results: dict[str, ToolResult] = {}

    def register(self, ci: CriticalInstruction) -> None:
        if ci.postcondition is None:
            raise PriorityInheritanceViolation(
                f"instruction {ci.instruction_id} tagged critical with no evaluable "
                f"postcondition; reject at planning time, do not inherit"
            )
        self.instructions[ci.instruction_id] = ci

    def record_tool_result(self, tr: ToolResult) -> None:
        self.tool_results[tr.tool_result_id] = tr

    def _evaluate(self, ci: CriticalInstruction) -> bool:
        # Postcondition is a key lookup into structured tool output, e.g.
        # "approvals.log:po_id" matches a signed entry for the specific PO.
        key = ci.postcondition
        for tr in self.tool_results.values():
            if tr.ok and key in tr.structured:
                ci.discharged_by = tr.tool_result_id
                return True
        return False

    def try_evict(self, instruction_id: str, effective_budget: int, pinned_cost: int) -> None:
        ci = self.instructions[instruction_id]
        if not self._evaluate(ci):
            # Instruction is unmet. Do NOT evict on executor utterance.
            if effective_budget - pinned_cost < self.min_progress_budget:
                raise PriorityInheritanceViolation(
                    f"priority inversion: {instruction_id} pinned and unmet, "
                    f"executor starved (effective={effective_budget}, "
                    f"pinned={pinned_cost}, min={self.min_progress_budget}); "
                    f"escalate to planner for re-scope, do not evict"
                )
            raise PriorityInheritanceViolation(
                f"attempted eviction of unmet critical instruction {instruction_id}; "
                f"no discharging tool result in ledger"
            )
        ci.pinned = False  # discharged by tool result, safe to release
