# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-losing-reversible-edit-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-losing-reversible-edit-provenance.warrant.json
# Markdown SHA-256:   8109f3f3c2ff0861d05b9c59f6e0d72c8fefbd757a87a38ddaa874a79c64059e
# Code AST SHA-256:   b3490b36ba08c467563cd23c453903cf8af065defaee940e7c19d6f3c149668c
# Verified Classes:   ProvenanceIntegrityError, PolicyEdit, ProvenanceStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceIntegrityError(RuntimeError):
    """Raised when a self-editing context policy would destroy reversible edit provenance."""
    pass


@dataclass
class PolicyEdit:
    seq: int
    op: str
    prior: Optional[int]
    new: int
    rationale_digest: str
    referents_pinned: bool


@dataclass
class ProvenanceStore:
    # C1: lives outside the policy-governed context; edit path cannot evict it.
    entries: list = field(default_factory=list)
    _last_seq: int = 0

    def attested_prior(self, op: str, authoritative_state: dict) -> Optional[int]:
        return authoritative_state.get(op)


def commit_policy_edit(
    store: ProvenanceStore,
    authoritative_state: dict,
    op: str,
    new_value: int,
    rationale: str,
    cited_referents: list,
    pinned_referents: set,
) -> PolicyEdit:
    # C1: reject if the edit path can reach the provenance store.
    if store is None or not hasattr(store, "entries"):
        raise ProvenanceIntegrityError(
            "provenance store unreachable or governed by edited policy; edit is irreversible"
        )

    # C2: every cited referent must be pinned or carry a digest.
    unpinned = [r for r in cited_referents if r not in pinned_referents]
    if unpinned and not rationale:
        raise ProvenanceIntegrityError(
            f"justification cites evictable referents {unpinned} with no digest; "
            "edit would dangle its own evidence"
        )

    # C3: prior value must be attested from authoritative state, never re-derived.
    prior = store.attested_prior(op, authoritative_state)
    if prior is None:
        raise ProvenanceIntegrityError(
            f"prior value for {op} not readable from authoritative state; "
            "refusing delta edit to prevent no-op masking of earlier edits"
        )

    if prior == new_value:
        # A no-op that hides a prior real edit is the exact failure observed at turn 47.
        raise ProvenanceIntegrityError(
            f"edit {op}:{prior}->{new_value} is a no-op; "
            "if a real edit preceded this, the chain is already corrupted"
        )

    digest = hashlib.sha256(rationale.encode()).hexdigest()
    store._last_seq += 1
    entry = PolicyEdit(
        seq=store._last_seq,
        op=op,
        prior=prior,
        new=new_value,
        rationale_digest=digest,
        referents_pinned=not unpinned,
    )
    store.entries.append(entry)
    authoritative_state[op] = new_value
    return entry


def replay(store: ProvenanceStore, initial_state: dict) -> dict:
    state = dict(initial_state)
    for e in store.entries:
        if e.prior != state.get(e.op):
            raise ProvenanceIntegrityError(
                f"replay divergence at seq {e.seq}: attested prior {e.prior} "
                f"!= replayed state {state.get(e.op)}"
            )
        state[e.op] = e.new
    return state
