# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-scratchpad-monotone-token-invariants-and-the-reasoning-trace-amnesia-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-scratchpad-monotone-token-invariants-and-the-reasoning-trace-amnesia-boundary.warrant.json
# Markdown SHA-256:   d0723c29536f65968d506654140bc960c51e057d51f4f8544eba9fdf53a3668a
# Code AST SHA-256:   248c3646b5c7d4d6aacfa563f02045d17cfd62d230af741c59882fcbf972e44f
# Verified Classes:   UnprovablePruneError, Trace, Scratchpad
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnprovablePruneError(RuntimeError):
    """Raised when a self-edit would remove a trace whose claims are not
    externally re-resolvable, laundering uncertainty into apparent fact."""
    pass


@dataclass
class Trace:
    trace_id: str
    claim: str
    confidence: str          # "established" | "hedged" | "unresolved"
    referent: Optional[str]  # artifact id / path / tool-result hash, or None
    hedges: list[str] = field(default_factory=list)


@dataclass
class Scratchpad:
    traces: dict[str, Trace] = field(default_factory=dict)
    obligations: list[str] = field(default_factory=list)


def self_edit(scratchpad: Scratchpad, prune_ids: list[str],
              retained_claims: dict[str, str]) -> Scratchpad:
    """Agent-initiated prune. Refuses if any pruned trace is unprovable or if
    the retained claim inflates confidence beyond the pruned union."""
    for tid in prune_ids:
        trace = scratchpad.traces.get(tid)
        if trace is None:
            continue
        if trace.confidence in ("hedged", "unresolved"):
            # Hedges have no external referent by construction; pruning them
            # silently converts known-unknown into unknown-unknown.
            raise UnprovablePruneError(
                f"cannot prune {tid}: confidence={trace.confidence!r} "
                f"has no committed referent; promote to obligation first"
            )
        if trace.referent is None:
            raise UnprovablePruneError(
                f"cannot prune {tid}: claim {trace.claim!r} not re-openable"
            )

    # Monotone-uncertainty check: retained text must not be more confident
    # than the union of the traces it replaces.
    for tid, new_claim in retained_claims.items():
        original = scratchpad.traces.get(tid)
        if original is None:
            continue
        if original.confidence != "established" and "established" in new_claim.lower():
            raise UnprovablePruneError(
                f"summary of {tid} inflates confidence: {new_claim!r}"
            )

    new_pad = Scratchpad(
        traces={k: v for k, v in scratchpad.traces.items() if k not in prune_ids},
        obligations=list(scratchpad.obligations),
    )
    return new_pad


def commit_referent(scratchpad: Scratchpad, trace_id: str, artifact_id: str) -> None:
    trace = scratchpad.traces[trace_id]
    trace.referent = artifact_id
    trace.confidence = "established"


# --- trigger trace ---
pad = Scratchpad(traces={
    "t6": Trace("t6", "parse_config returned partial dict; retry_policy missing",
                confidence="hedged", referent=None,
                hedges=["retry_policy not yet confirmed"]),
    "t9": Trace("t9", "config keyed by section name",
                confidence="established", referent="tool-result:sha256:ab12"),
})

# The agent tries to compress t6 into a settled fact at step 14.
try:
    self_edit(pad, prune_ids=["t6"], retained_claims={
        "t6": "established that parse_config returns a dict keyed by section name",
    })
except UnprovablePruneError as e:
    # Correct response: commit the partial result, emit an obligation, retry.
    commit_referent(pad, "t6", artifact_id="file:partial_config.json")
    pad.obligations.append("resolve retry_policy before indexing config")
    pad = self_edit(pad, prune_ids=["t6"], retained_claims={
        "t6": "parse_config partial; retry_policy pending (see obligation)",
    })
    assert "resolve retry_policy" in pad.obligations
    print("prune accepted after referent commitment:", e)
