# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-using-a-learned-relevance-policy-and-evicts-the-provenance-record-of-a-still-pending-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-using-a-learned-relevance-policy-and-evicts-the-provenance-record-of-a-still-pending-tool.warrant.json
# Markdown SHA-256:   95901a8826de3435fee72babed7f1058ed0ff7b184e1d84b0689e720b923c068
# Code AST SHA-256:   ff646aeab6c948ede6b50a608ad8fe4ea4c2b96931a38df2a7a206eb00638b81
# Verified Classes:   ObligationIntegrityError, Obligation, ObligationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ObligationIntegrityError(RuntimeError):
    """Raised when a self-editing compaction step would evict or summarize a
    live obligation record, or when a reconstructed span fails hash validation."""
    pass


@dataclass
class Obligation:
    obligation_id: str
    kind: str                 # "tool_call" | "handoff" | "verification"
    payload_hash: str         # sha256 of the full argument/intent payload
    branch: str               # reasoning branch the result must re-attach to
    resolved: bool = False


@dataclass
class ObligationLedger:
    _records: dict = field(default_factory=dict)

    def issue(self, obligation_id, kind, payload, branch):
        h = hashlib.sha256(payload.encode()).hexdigest()
        self._records[obligation_id] = Obligation(obligation_id, kind, h, branch)

    def resolve(self, obligation_id, result_payload):
        rec = self._records.get(obligation_id)
        if rec is None:
            raise ObligationIntegrityError(
                f"result for unknown obligation {obligation_id!r}: "
                f"binding was evicted before resolution")
        rec.resolved = True
        return rec.branch

    def live_ids(self):
        return {k for k, v in self._records.items() if not v.resolved}


def compact(window_spans, ledger, relevance_policy, threshold):
    """Apply a learned relevance policy to the evictable context, but refuse to
    let it touch spans bound to live obligations."""
    live = ledger.live_ids()
    pinned, evictable = [], []
    for span in window_spans:
        bound = span.get("obligation_id")
        if bound in live:
            if span.get("kind") == "summary":
                raise ObligationIntegrityError(
                    f"compactor attempted to summarize live obligation {bound!r}; "
                    f"summary-level retention loses branch binding")
            pinned.append(span)
        else:
            evictable.append(span)

    scores = relevance_policy(evictable)
    survivors = [s for s, sc in zip(evictable, scores) if sc >= threshold]
    return pinned + survivors


def reconstruct(obligation_id, ledger, external_store):
    rec = ledger._records.get(obligation_id)
    if rec is None or rec.resolved:
        raise ObligationIntegrityError(
            f"cannot reconstruct {obligation_id!r}: no live ledger record")
    payload = external_store.fetch(obligation_id)
    if hashlib.sha256(payload.encode()).hexdigest() != rec.payload_hash:
        raise ObligationIntegrityError(
            f"hash mismatch reconstructing {obligation_id!r}: "
            f"external store returned mutated payload")
    return payload, rec.branch
