# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-summarize-its-own-working-context-the-irreversible-distillation-trap-in-model-driven-context-rewriting.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-summarize-its-own-working-context-the-irreversible-distillation-trap-in-model-driven-context-rewriting.warrant.json
# Markdown SHA-256:   1a301ff3141252fba064c9aade3e61618ed4a6999b73b468ac9b3a7bc2bcacae
# Code AST SHA-256:   cc90fa4183eb2a97b10a4cce6669445ffb9eae4f41d9dacd159298d4cb1cb0de
# Verified Classes:   IrreversibleDistillationError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class IrreversibleDistillationError(RuntimeError):
    """Raised when a self-rewrite would destroy a single-referent obligation."""


@dataclass
class Span:
    span_id: str
    text: str
    obligations: list[str] = field(default_factory=list)  # deferred failures, constraints, side-effects
    pointer_backed: bool = False          # retained in addressable store w/ hash
    re_fetchable: bool = False            # tool result reproducible on demand


def _hash(text: str) -> str:
    return hashlib.sha256(text.encode()).hexdigest()[:16]


def plan_compaction(spans: Iterable[Span], live_window_ids: set[str]) -> dict:
    """Partition spans into distillable vs must-retain. Refuses unsafe distillation."""
    distill, retain = [], []
    for s in spans:
        duplicated = any(
            other.span_id in live_window_ids and other.obligations == s.obligations
            for other in spans if other.span_id != s.span_id
        )
        if not s.obligations or duplicated:
            distill.append(s.span_id)
            continue
        # single-referent obligation: safe only if pointer-backed AND re-fetchable
        if s.pointer_backed and s.re_fetchable:
            retain.append((s.span_id, "pointer", _hash(s.text)))
        else:
            raise IrreversibleDistillationError(
                f"span {s.span_id} carries obligation {s.obligations!r} "
                f"with no live duplicate and no recoverable pointer; "
                f"refusing lossy self-distillation"
            )
    return {"distill": distill, "retain": retain}


def guarded_self_rewrite(spans: list[Span], live_window_ids: set[str]) -> dict:
    plan = plan_compaction(spans, live_window_ids)
    # Only after the plan is proven safe do we emit a rewrite directive.
    return {
        "action": "rewrite",
        "distill_spans": plan["distill"],
        "retained_obligations": plan["retain"],
        "audit_log": [{"span": sid, "decision": "distill"} for sid in plan["distill"]],
    }


if __name__ == "__main__":
    spans = [
        Span("t14", "FAILED test_idempotency expected 1 got 2",
             obligations=["deferred_failure:test_idempotency"]),
        Span("t20", "user: do not cite pre-2020 sources",
             obligations=["constraint:no_pre_2020"]),
        Span("t39", "schema migration step 1", obligations=[]),
    ]
    try:
        guarded_self_rewrite(spans, live_window_ids={"t39"})
    except IrreversibleDistillationError as e:
        print("REFUSED:", e)  # correct: escalate / checkpoint externally instead
