# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-loss-of-executable-state-during-hierarchical-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-loss-of-executable-state-during-hierarchical-context-compaction.warrant.json
# Markdown SHA-256:   b4d732745594cf28d336b331b03c8ad5ae4972db02179ec5f413b0c6fc428d6b
# Code AST SHA-256:   6d47a830314403ed4a875ac3f2c9312147639c1fcaad779b2f995f199f3b163f
# Verified Classes:   CompactionRefused, HandleState, ExecutableState, BindingConstraint, Sidecar
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class CompactionRefused(RuntimeError):
    """Raised when context compaction would destroy executable or binding state."""


class HandleState(Enum):
    PENDING = "pending"        # accepted, not terminal — NOT safe to summarize away
    COMMITTED = "committed"    # terminal success — narrative-safe
    FAILED = "failed"          # terminal failure — narrative-safe


@dataclass
class ExecutableState:
    handle_id: str
    kind: str                  # "write_batch" | "stream_cursor" | "tool_call"
    state: HandleState
    payload: dict[str, Any] = field(default_factory=dict)


@dataclass
class BindingConstraint:
    predicate: str             # machine-checkable, e.g. "content_hash NOT IN seen_set"
    scope: str
    source_turn: int


@dataclass
class Sidecar:
    executable: list[ExecutableState] = field(default_factory=list)
    constraints: list[BindingConstraint] = field(default_factory=list)


def freeze_state(
    open_handles: list[ExecutableState],
    constraints: list[BindingConstraint],
    reclaimable_narrative_tokens: int,
    tokens_needed: int,
) -> Sidecar:
    """
    Phase 1 of compaction. Must complete before any token is reclaimed.
    Refuses if executable state cannot be fully captured or if pending
    handles would be lost to summarization.
    """
    pending = [h for h in open_handles if h.state is HandleState.PENDING]
    if pending:
        # Pending handles have no prose representation; summarizing them is
        # how phantom-completion incidents happen.
        raise CompactionRefused(
            f"{len(pending)} non-terminal handle(s) cannot be summarized: "
            f"{[h.handle_id for h in pending]}. Drain to terminal state first."
        )

    for c in constraints:
        if not c.predicate or " " in c.predicate and "NOT IN" not in c.predicate.upper():
            raise CompactionRefused(
                f"constraint from turn {c.source_turn} has no checkable predicate; "
                f"refusing to let summarizer paraphrase it into narrative."
            )

    if reclaimable_narrative_tokens < tokens_needed:
        raise CompactionRefused(
            f"narrative reclaim ({reclaimable_narrative_tokens}) insufficient for "
            f"need ({tokens_needed}); executable state is irreducible — "
            f"checkpoint-restart required instead of compaction."
        )

    return Sidecar(executable=list(open_handles), constraints=list(constraints))


def resume_context(sidecar: Sidecar, summary_text: str) -> str:
    """
    Phase 2. Sidecar is authoritative over the summary; re-injected first.
    """
    if any(h.state is HandleState.PENDING for h in sidecar.executable):
        raise CompactionRefused("resume attempted with non-terminal handle in sidecar.")
    frozen = "\n".join(
        f"[EXEC] {h.kind}:{h.handle_id}={h.state.value} {h.payload}"
        for h in sidecar.executable
    )
    binds = "\n".join(
        f"[BIND] {c.predicate} (scope={c.scope}, turn={c.source_turn})"
        for c in sidecar.constraints
    )
    return f"=== FROZEN STATE (authoritative) ===\n{frozen}\n{binds}\n\n=== NARRATIVE SUMMARY (non-authoritative) ===\n{summary_text}"
