# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-of-its-own-context-window-before-the-rewrite-policy-invalidates-the-evidence-it-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-of-its-own-context-window-before-the-rewrite-policy-invalidates-the-evidence-it-depends-on.warrant.json
# Markdown SHA-256:   9c9b5590557bb309a7fdbc7672d99fa0e1bfd8f46eefacb61d028c730ce638cd
# Code AST SHA-256:   7a7703a83b2d93c61480d96ac02906b33b88595d5f4190e97e74e1ef21d5d22e
# Verified Classes:   PruneInvariantViolation, Span, RewritePolicy, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PruneInvariantViolation(RuntimeError):
    """Raised when a model-driven context rewrite would destroy evidence
    it (or a later step) depends on. Bounds the self-editing failure mode."""


@dataclass
class Span:
    span_id: str
    text: str
    is_raw_tool_output: bool = False
    contains_verbatim_literal: bool = False
    is_derived_digest: bool = False


@dataclass
class RewritePolicy:
    prior_compaction_passes: int = 0
    remaining_task_needs_verification: bool = True  # assume true if unknown


class ContextWindow:
    def __init__(self, spans: list[Span], evidence_store: dict[str, str]):
        self.spans = {s.span_id: s for s in spans}
        self.evidence_store = evidence_store  # content-hash -> verbatim text
        self.passes = 0

    def _externalize(self, span: Span) -> str:
        h = hashlib.sha256(span.text.encode()).hexdigest()
        self.evidence_store[h] = span.text
        return h

    def prune(self, policy: RewritePolicy, candidate_ids: list[str]) -> list[str]:
        """Commit a model-driven prune. Returns hashes the digest must carry.
        Refuses (raises) if the rewrite would violate C1-C4."""
        if policy.prior_compaction_passes >= 1:
            # C3: summarizing a summary compounds error; must re-ground first.
            raise PruneInvariantViolation(
                "second-or-later compaction pass: input is a derived digest, "
                "not primary evidence; re-ground against evidence_store before pruning"
            )

        hashes = []
        for sid in candidate_ids:
            span = self.spans[sid]
            if span.is_raw_tool_output and policy.remaining_task_needs_verification:
                # C1/C2: raw output contradicting narration must survive verbatim.
                hashes.append(self._externalize(span))
                continue
            if span.contains_verbatim_literal:
                # exact literals (hashes, exit codes, "true" vs true) must be
                # re-fetchable, never summarized away.
                hashes.append(self._externalize(span))
                continue
            if span.is_derived_digest:
                raise PruneInvariantViolation(
                    f"span {sid} is already a digest; refusing to compress a "
                    "derived artifact (self-amplification of prior error)"
                )
            # pure narration of side-effect-free, re-derivable actions: safe to drop
            del self.spans[sid]

        self.passes += 1
        return hashes

    def resolve(self, content_hash: str) -> str:
        if content_hash not in self.evidence_store:
            raise PruneInvariantViolation(
                f"digest references {content_hash[:12]}... but no verbatim source "
                "survives; ground truth was deleted by an earlier prune"
            )
        return self.evidence_store[content_hash]
