# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-agents-from-silently-deleting-the-evidence-their-own-verifier-needs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-agents-from-silently-deleting-the-evidence-their-own-verifier-needs.warrant.json
# Markdown SHA-256:   1f5ee9275ca52751ff3ed518e1dcaaf686b92e7470069c54cf29357252adefad
# Code AST SHA-256:   5dcf7fa1f69aa2dbfae43bd30f2533918e82a439bdfd72a7787aebdbdb0eb593
# Verified Classes:   EvidentiaryEditError, MemoryEntry, SelfEditingMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EvidentiaryEditError(RuntimeError):
    """Raised when a memory rewrite would erase evidence a verifier needs."""
    pass


@dataclass
class MemoryEntry:
    kind: str                 # "evidence" | "reasoning"
    content: str
    tool_call_id: Optional[str] = None
    content_hash: Optional[str] = None
    timestamp: Optional[float] = None


def _hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


@dataclass
class SelfEditingMemory:
    entries: list = field(default_factory=list)
    # beliefs the live answer depends on, by evidence hash
    live_dependencies: set = field(default_factory=set)

    def add_evidence(self, content: str, tool_call_id: str, ts: float) -> str:
        h = _hash(content)
        self.entries.append(MemoryEntry(
            kind="evidence", content=content, tool_call_id=tool_call_id,
            content_hash=h, timestamp=ts,
        ))
        return h

    def add_reasoning(self, content: str) -> None:
        self.entries.append(MemoryEntry(kind="reasoning", content=content))

    def depend_on(self, evidence_hash: str) -> None:
        self.live_dependencies.add(evidence_hash)

    def prune(self, predicate) -> None:
        """Remove entries matching predicate, refusing to erase live evidence."""
        survivors = []
        for e in self.entries:
            if not predicate(e):
                survivors.append(e)
                continue
            # Capacity edits on reasoning are safe; evidence is not.
            if e.kind == "reasoning":
                continue
            if e.content_hash in self.live_dependencies:
                raise EvidentiaryEditError(
                    f"refusing to prune evidence {e.tool_call_id!r}: "
                    f"hash {e.content_hash[:12]} is a live dependency of the "
                    f"current answer; downgrade to a reference instead"
                )
            survivors.append(e)  # non-live evidence may be referenced, not dropped
        self.entries = survivors

    def downgrade_to_reference(self, evidence_hash: str) -> None:
        """Keep hash + pointer, drop full text. Preserves replayability."""
        for e in self.entries:
            if e.content_hash == evidence_hash and e.kind == "evidence":
                e.content = f"<ref hash={e.content_hash} call={e.tool_call_id}>"
                return
        raise EvidentiaryEditError(f"no evidence entry for hash {evidence_hash[:12]}")


def rewrite_scratchpad(mem: SelfEditingMemory, new_summary: str) -> None:
    """Agent-driven rewrite: compress reasoning, never live evidence."""
    if not mem.live_dependencies:
        raise EvidentiaryEditError(
            "cannot rewrite: no live dependencies recorded; auditability unknown"
        )
    # Reasoning prose is re-derivable and safe to drop.
    mem.prune(lambda e: e.kind == "reasoning")
    mem.add_reasoning(new_summary)
    # Every live dependency must still be resolvable in memory.
    present = {e.content_hash for e in mem.entries if e.kind == "evidence"}
    missing = mem.live_dependencies - present
    if missing:
        raise EvidentiaryEditError(
            f"rewrite orphaned live dependencies: {sorted(h[:12] for h in missing)}"
        )
