# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-severed-its-own-edit-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-severed-its-own-edit-provenance.warrant.json
# Markdown SHA-256:   338dcfed3f7380e31295b8b42d3863827e507c945d1afeb277673df4811f5bcd
# Code AST SHA-256:   ef2b7088108902ef3a642631dcd47e20db9f8613af8686a455b23ee238097229
# Verified Classes:   ProvenanceError, ProvenanceClass, Span, ProvenanceSidecar
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ProvenanceError(RuntimeError):
    """Raised when a self-edit severs or forges edit provenance."""
    pass


class ProvenanceClass(Enum):
    TOOL_OUTPUT = "tool_output"
    MODEL_SUMMARY = "model_summary"
    INFERRED_FROM_SUMMARY = "inferred_from_summary"


@dataclass(frozen=True)
class Span:
    span_id: str
    content_hash: str
    provenance: ProvenanceClass
    edit_cycle: int
    hedges_preserved: bool


@dataclass
class ProvenanceSidecar:
    # Append-only; the model has no write authority over this structure.
    spans: dict[str, Span] = field(default_factory=dict)
    tombstones: dict[str, int] = field(default_factory=dict)  # span_id -> pruned_at_cycle
    _cycle: int = 0

    def next_cycle(self) -> int:
        self._cycle += 1
        return self._cycle

    def record(self, span: Span) -> None:
        if span.span_id in self.spans:
            raise ProvenanceError(
                f"span {span.span_id} already recorded; edits are append-only"
            )
        self.spans[span.span_id] = span

    def tombstone(self, span_id: str, cycle: int) -> None:
        if span_id not in self.spans:
            raise ProvenanceError(f"cannot tombstone unknown span {span_id}")
        self.tombstones[span_id] = cycle


def apply_compaction(
    sidecar: ProvenanceSidecar,
    source_span_ids: list[str],
    summary_text: str,
    hedges_preserved: bool,
) -> Span:
    """Model-proposed compaction. The model supplies source ids and summary;
    the sidecar (not the model) assigns provenance and cycle."""
    cycle = sidecar.next_cycle()

    for sid in source_span_ids:
        if sid not in sidecar.spans:
            raise ProvenanceError(
                f"compaction cites unknown span {sid}; provenance already severed"
            )
        if sid in sidecar.tombstones:
            raise ProvenanceError(
                f"compaction cites tombstoned span {sid} (pruned at cycle "
                f"{sidecar.tombstones[sid]}); source is unrecoverable"
            )

    # Provenance-class collapse check: if any source is itself a summary,
    # the output cannot claim tool_output-level grounding.
    source_classes = {sidecar.spans[s].provenance for s in source_span_ids}
    if ProvenanceClass.MODEL_SUMMARY in source_classes or \
       ProvenanceClass.INFERRED_FROM_SUMMARY in source_classes:
        out_class = ProvenanceClass.INFERRED_FROM_SUMMARY
    else:
        out_class = ProvenanceClass.MODEL_SUMMARY

    # Hedge erosion guard: summaries of hedged material must retain hedges.
    source_hedged = any(not sidecar.spans[s].hedges_preserved for s in source_span_ids)
    if source_hedged and not hedges_preserved:
        raise ProvenanceError(
            "compaction dropped epistemic qualifiers from hedged source; "
            "estimate would be laundered into fact"
        )

    new_span = Span(
        span_id=f"span_c{cycle}_{hashlib.sha256(summary_text.encode()).hexdigest()[:8]}",
        content_hash=hashlib.sha256(summary_text.encode()).hexdigest(),
        provenance=out_class,
        edit_cycle=cycle,
        hedges_preserved=hedges_preserved,
    )

    for sid in source_span_ids:
        sidecar.tombstone(sid, cycle)
    sidecar.record(new_span)
    return new_span
