# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-its-own-pruning-pass-when-a-self-edited-context-window-severs-a-reasoning-trace-from-its-tool-call-provenanc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-its-own-pruning-pass-when-a-self-edited-context-window-severs-a-reasoning-trace-from-its-tool-call-provenanc.warrant.json
# Markdown SHA-256:   fb472044829c80afed2ddd3b07f3610e645273a7c867cb7c567eb43a11ac579a
# Code AST SHA-256:   1b4ece10b8d2f10bb2726ff5c82fe3f9ca6b8d48fe5344dfe264b0b681b16910
# Verified Classes:   ProvenanceSeveranceError, ToolRecord, Conclusion, PruneCandidate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceSeveranceError(RuntimeError):
    """Raised when a pruning pass would leave a verified conclusion without a resolvable tool-call binding."""
    pass


@dataclass
class ToolRecord:
    call_id: str
    raw_output: str

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.raw_output.encode()).hexdigest()


@dataclass
class Conclusion:
    text: str
    verified: bool
    provenance_call_id: str | None
    provenance_hash: str | None


@dataclass
class PruneCandidate:
    trace_id: str
    conclusion: Conclusion
    restated_in: "Conclusion | None" = None


def apply_pruning_pass(
    candidates: list[PruneCandidate],
    tool_records: dict[str, ToolRecord],
) -> list[str]:
    """Return trace_ids safe to delete. Reject the entire pass if any deletion severs a verified conclusion."""
    deletable: list[str] = []
    for cand in candidates:
        concl = cand.conclusion
        if not concl.verified:
            deletable.append(cand.trace_id)
            continue
        # Collapse is only safe if a later restatement inherits the binding.
        if cand.restated_in is not None:
            r = cand.restated_in
            if r.provenance_call_id == concl.provenance_call_id and r.provenance_hash == concl.provenance_hash:
                deletable.append(cand.trace_id)
                continue
        # Sole binding: check the record still resolves and matches its hash.
        rec = tool_records.get(concl.provenance_call_id or "")
        if rec is None or rec.content_hash != concl.provenance_hash:
            raise ProvenanceSeveranceError(
                f"pruning trace {cand.trace_id} would orphan verified conclusion "
                f"{concl.text!r}: binding {concl.provenance_call_id!r} unresolvable or hash-mismatched"
            )
        # Sole surviving binding for a verified conclusion: must be retained.
        raise ProvenanceSeveranceError(
            f"pruning trace {cand.trace_id} would sever sole binding for verified conclusion "
            f"{concl.text!r} -> {concl.provenance_call_id!r}; demote to hypothesis or retain"
        )
    return deletable


def self_edit(candidates, tool_records, budget_ok: bool) -> list[str]:
    if not budget_ok:
        return []
    try:
        return apply_pruning_pass(candidates, tool_records)
    except ProvenanceSeveranceError:
        # Fall back to coarse coherent compaction rather than partial surgical deletion.
        raise ProvenanceSeveranceError(
            "self-edit rejected: fall back to whole-prefix summarization preserving provenance"
        )
