# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-destroying-the-provenance-of-the-tokens-they-keep.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-destroying-the-provenance-of-the-tokens-they-keep.warrant.json
# Markdown SHA-256:   39fa66275a5b4385083c9c799eb974a3e057ff0df60175bd58cb8ff2f4f53f6f
# Code AST SHA-256:   f749726787547e1ca56604f9e8438c3de47d009f99f9d2d82edc2449345fd590
# Verified Classes:   ProvenanceViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

SourceClass = Literal["user", "tool", "peer", "model", "derived"]


class ProvenanceViolation(RuntimeError):
    """Raised when a self-edited span cannot be traced to its origins."""


@dataclass
class Span:
    span_id: str
    authored_by: str          # who wrote this span (e.g. "compactor")
    source_class: SourceClass # authority class of the *content*
    derived_from: list[str] = field(default_factory=list)  # parent span_ids
    text: str = ""


# Authority ordering: lower index = stronger ground truth.
_AUTHORITY = ["user", "tool", "peer", "model", "derived"]


def _weakest(classes: list[SourceClass]) -> SourceClass:
    return max(classes, key=lambda c: _AUTHORITY.index(c))


def admit_edit(editor: str, parents: list[Span], new_text: str,
               span_id: str) -> Span:
    """
    Write-time gate for any model-driven prune/rewrite/re-rank output.
    Rejects edits that mint provenance the editor does not own.
    """
    if not parents:
        raise ProvenanceViolation(
            f"editor={editor} span={span_id}: no parents; a self-edit "
            f"cannot assert content with no origins."
        )

    parent_ids = [p.span_id for p in parents]
    if len(set(parent_ids)) != len(parent_ids):
        raise ProvenanceViolation(
            f"span={span_id}: duplicate parent ids {parent_ids}; "
            f"derived_from must be a set of distinct origins."
        )

    # Inherit the weakest authority among parents; never upgrade.
    inherited = _weakest([p.source_class for p in parents])

    # Reject any attempt to claim a stronger class than the parents allow.
    if _AUTHORITY.index(inherited) < _AUTHORITY.index("derived"):
        # Parents are all stronger than 'derived'; the summary is still
        # 'derived' because its author is the editor, not the origin.
        pass

    return Span(
        span_id=span_id,
        authored_by=editor,
        source_class="derived",
        derived_from=parent_ids,
        text=new_text,
    )


def validate_span(span: Span) -> None:
    if span.source_class == "derived" and not span.derived_from:
        raise ProvenanceViolation(
            f"span={span.span_id}: derived span with empty derived_from; "
            f"provenance laundered by editor={span.authored_by}."
        )
    if span.authored_by != "user" and span.source_class == "user":
        raise ProvenanceViolation(
            f"span={span.span_id}: authored_by={span.authored_by} cannot "
            f"claim source_class=user; authority upgrade forbidden."
        )


def compact(editor: str, spans: list[Span], budget: int) -> list[Span]:
    """
    Minimal safe compactor: reorder + exact-dedup only. Paraphrase is
    delegated to admit_edit, which forces derived provenance.
    """
    seen, kept = set(), []
    for s in spans:
        validate_span(s)
        if s.text in seen:
            continue
        seen.add(s.text)
        kept.append(s)
    if sum(len(s.text) for s in kept) <= budget:
        return kept

    # Budget exceeded: emit a derived summary with full back-pointers,
    # never a bare paraphrase.
    summary = admit_edit(
        editor=editor,
        parents=kept,
        new_text="<summary of kept spans>",
        span_id="summary-1",
    )
    validate_span(summary)
    return [summary]
