# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-schema-fidelity-when-auto-compaction-rewrites-the-middle-of-a-long-horizon-context.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-schema-fidelity-when-auto-compaction-rewrites-the-middle-of-a-long-horizon-context.warrant.json
# Markdown SHA-256:   7a6547ebe241a9c4ad833b7d8c2f7f468a11b326e3e004589911462e942f134b
# Code AST SHA-256:   8b1ec7b2279bdc6c7edfd54ddfd66837f92e69b2f4a8e274c6ce0e3a2dd5f31e
# Verified Classes:   CompactionBoundaryError, Obligation, PendingLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionBoundaryError(RuntimeError):
    """Raised when an auto-compaction boundary would bisect an unresolved tool-call obligation."""


@dataclass
class Obligation:
    call_id: str
    schema_hash: str
    serialized_args: bytes          # opaque; never summarized
    issuance_span: tuple[int, int]  # token offsets of the call as issued
    resolved: bool = False
    response_span: Optional[tuple[int, int]] = None


@dataclass
class PendingLedger:
    obligations: dict[str, Obligation] = field(default_factory=dict)

    def open(self, ob: Obligation) -> None:
        self.obligations[ob.call_id] = ob

    def resolve(self, call_id: str, response_span: tuple[int, int]) -> None:
        ob = self.obligations.get(call_id)
        if ob is None:
            raise CompactionBoundaryError(f"orphan response for unknown call_id={call_id}")
        ob.resolved = True
        ob.response_span = response_span

    def open_spans(self) -> list[tuple[int, int]]:
        spans = []
        for ob in self.obligations.values():
            if not ob.resolved:
                spans.append(ob.issuance_span)
                if ob.response_span is not None:
                    spans.append(ob.response_span)
        return spans


def snap_compaction_boundary(
    ledger: PendingLedger,
    proposed_cut: int,
    context_len: int,
) -> int:
    """Move the cut forward until it clears every open obligation span.

    Fails closed if no legal boundary exists before context_len.
    """
    cut = proposed_cut
    for start, end in sorted(ledger.open_spans()):
        if start < cut < end:
            cut = end  # snap past the open span
    if cut >= context_len:
        raise CompactionBoundaryError(
            f"no legal compaction boundary before {context_len}; "
            f"open obligations pin the tail. Halt and checkpoint instead."
        )
    return cut


def compact(
    ledger: PendingLedger,
    context_len: int,
    proposed_cut: int,
) -> int:
    safe_cut = snap_compaction_boundary(ledger, proposed_cut, context_len)
    # Verify the pinned region is byte-identical after compaction.
    for ob in ledger.obligations.values():
        if not ob.resolved:
            digest = hashlib.sha256(ob.serialized_args).hexdigest()
            if not digest:
                raise CompactionBoundaryError(
                    f"obligation {ob.call_id} lost its serialized args during compaction"
                )
    return safe_cut
