# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-window-has-silently-orphaned-its-own-revision-history.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-window-has-silently-orphaned-its-own-revision-history.warrant.json
# Markdown SHA-256:   44dbaab6d8fc2bffe2c884c7c3f47cd19b3cff488dbd98478bdaa5f575356e86
# Code AST SHA-256:   5bb9bf01d45b50ef3404fbe875857ef60d36e2635018df364d8c8b591f09c833
# Verified Classes:   OrphanedRevisionError, Clause, Revision
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class OrphanedRevisionError(RuntimeError):
    """Raised when a self-authored revision cannot be tied to a live superseded clause."""
    pass


@dataclass(frozen=True)
class Clause:
    clause_id: str
    text: str
    is_root: bool

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


@dataclass(frozen=True)
class Revision:
    text: str
    supersedes_id: str | None
    supersedes_hash: str | None
    rationale: str | None


def apply_revision(window: dict[str, Clause], rev: Revision) -> dict[str, Clause]:
    """
    Apply a self-authored revision to the live context window.
    Enforces: every non-root revision must carry a supersession edge whose
    target still exists in the window AND whose content hash matches.
    """
    if rev.supersedes_id is None:
        # Root instructions are the only ones allowed to have no edge.
        raise OrphanedRevisionError(
            f"revision has no supersession edge and is not a root instruction: "
            f"{rev.text[:60]!r}"
        )

    target = window.get(rev.supersedes_id)
    if target is None:
        raise OrphanedRevisionError(
            f"revision supersedes {rev.supersedes_id!r} but that clause is absent "
            f"from the window (deleted by compaction rather than relocated)"
        )

    if rev.supersedes_hash != target.content_hash():
        raise OrphanedRevisionError(
            f"supersession edge hash mismatch for {rev.supersedes_id!r}: "
            f"edge claims {rev.supersedes_hash!r}, live clause is {target.content_hash()!r} "
            f"(possible edge forgery or paraphrased target)"
        )

    if rev.rationale is None or not rev.rationale.strip():
        raise OrphanedRevisionError(
            f"revision of {rev.supersedes_id!r} carries no rationale; "
            f"provenance would decay on next compaction"
        )

    new_window = dict(window)
    new_window[rev.supersedes_id] = Clause(
        clause_id=rev.supersedes_id,
        text=rev.text,
        is_root=False,
    )
    return new_window


def compact(window: dict[str, Clause], live_edges: set[str]) -> dict[str, Clause]:
    """
    Compaction pass: may relocate clauses but must not paraphrase any clause
    that is the target of a live supersession edge.
    """
    out = {}
    for cid, clause in window.items():
        if cid in live_edges:
            out[cid] = clause  # opaque: no rewrite allowed
        else:
            out[cid] = clause  # summarizer would run here for non-edge targets
    return out
