# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-authored-context-diff-that-its-own-validator-scores-as-lossless.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-authored-context-diff-that-its-own-validator-scores-as-lossless.warrant.json
# Markdown SHA-256:   106e3b52387111e2e54cb8f7a525a1645c0d22ee4bd0d403297147c5a619efeb
# Code AST SHA-256:   e899363048b671e0c5984bc9c25f5ea625a6fdba36b2a2bdf9f27eecd049ce58
# Verified Classes:   UnverifiableContextDiff, Span, ContextDiff, PinnedStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class UnverifiableContextDiff(RuntimeError):
    """Raised when a self-authored context diff removes content whose loss
    the validator cannot detect from the post-diff state alone."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    is_prohibition: bool = False
    owner_key: str | None = None

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


@dataclass
class ContextDiff:
    removed: list[Span] = field(default_factory=list)
    reordered: list[Span] = field(default_factory=list)


@dataclass
class PinnedStore:
    """Prohibitions and attestations the diff is forbidden to write."""
    pinned_hashes: set[str] = field(default_factory=set)
    pinned_prohibitions: dict[str, str] = field(default_factory=dict)

    def attests(self, span: Span) -> bool:
        if span.is_prohibition and span.text in self.pinned_prohibitions.values():
            return True
        return span.content_hash() in self.pinned_hashes


def audit_self_diff(
    diff: ContextDiff,
    snapshot: Iterable[Span],
    pinned: PinnedStore,
    validator_reads_post_diff_only: bool,
) -> None:
    """
    Refuse a self-authored diff when loss is undetectable from the post-diff
    state. Reference independence is the load-bearing invariant.
    """
    snapshot_by_id = {s.span_id: s for s in snapshot}

    # Invariant 1: the validator must not evaluate against the buffer it edits.
    if validator_reads_post_diff_only:
        raise UnverifiableContextDiff(
            "validator reads post-diff buffer; losslessness check is circular"
        )

    for span in diff.removed:
        if pinned.attests(span):
            continue
        # Invariant 2: a prohibition whose role lives only inside itself
        # cannot be checked after removal.
        if span.is_prohibition:
            raise UnverifiableContextDiff(
                f"prohibition span {span.span_id!r} removed without pinned attestation"
            )
        # Invariant 3: any non-redundant removal must be attested by hash.
        raise UnverifiableContextDiff(
            f"span {span.span_id!r} removed with no independent attestation"
        )

    for span in diff.reordered:
        original = snapshot_by_id.get(span.span_id)
        if original is None:
            raise UnverifiableContextDiff(
                f"reordered span {span.span_id!r} absent from snapshot"
            )
        # Invariant 4: reorder must preserve the owner-key binding, else
        # adjacency-based relations are silently destroyed.
        if original.owner_key != span.owner_key:
            raise UnverifiableContextDiff(
                f"reorder of {span.span_id!r} breaks owner binding "
                f"{original.owner_key!r} -> {span.owner_key!r}"
            )


def safe_commit(
    diff: ContextDiff,
    snapshot: Iterable[Span],
    pinned: PinnedStore,
    validator_reads_post_diff_only: bool,
) -> str:
    audit_self_diff(diff, snapshot, pinned, validator_reads_post_diff_only)
    return "committed"
