# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-rewriting-scratchpad-policies-against-provenance-collapse-during-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-rewriting-scratchpad-policies-against-provenance-collapse-during-compaction.warrant.json
# Markdown SHA-256:   ee8091f87902f8795c683e79999e3ad0822adbeb30b35fbaf70989a408937ce8
# Code AST SHA-256:   10db43aabc8950999de940b35b95c3b5efa5f8a67e58faff9a1e8be6f1f424f7
# Verified Classes:   ProvenanceCollapseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceCollapseError(RuntimeError):
    """Raised when a scratchpad rewrite would destroy re-expandability of a
    literal or invert a relational fact, converting checkable state into
    asserted state that the next reasoning step cannot falsify."""
    pass


LITERAL_MARKERS = ("path", "line", "number", "error_string", "exit_status", "hash", "id")
RELATIONAL_MARKERS = ("expected", "observed", "before", "after", "input", "output")


def validate_rewrite(original_claims: list[dict], proposed_text: str, reexpandable_ids: set[str]) -> None:
    """Enforce the provenance-preserving rewrite discipline before commit.

    original_claims: each dict has 'kind' in {'literal','relational','inferred'},
                     'value', and optionally 'handle' (an id the runtime can re-expand).
    proposed_text:   the model's proposed consolidated scratchpad.
    reexpandable_ids: handles currently resolvable by the runtime.
    """
    for claim in original_claims:
        kind = claim["kind"]
        value = claim["value"]
        handle = claim.get("handle")

        if kind == "literal":
            still_present = value in proposed_text
            reachable = handle is not None and handle in reexpandable_ids
            if not (still_present or reachable):
                raise ProvenanceCollapseError(
                    f"Literal {value!r} was paraphrased away and has no re-expandable "
                    f"handle (handle={handle!r}, resolvable={handle in reexpandable_ids if handle else False}). "
                    f"Rewrite would convert a checkable fact into an asserted one."
                )

        elif kind == "relational":
            # polarity check: both operands must survive, in order
            lhs, rhs = claim["lhs"], claim["rhs"]
            if not (lhs in proposed_text and rhs in proposed_text):
                raise ProvenanceCollapseError(
                    f"Relational fact {lhs!r} -> {rhs!r} lost an operand; "
                    f"polarity cannot be verified and may have inverted."
                )
            if proposed_text.index(rhs) < proposed_text.index(lhs):
                raise ProvenanceCollapseError(
                    f"Relational fact {lhs!r} -> {rhs!r} had its operands reordered; "
                    f"diagnosis direction may be inverted."
                )

        elif kind == "inferred":
            # inference must remain syntactically distinguishable from observation
            if "INFERRED" not in proposed_text:
                raise ProvenanceCollapseError(
                    f"Inferred claim {value!r} was flattened into observed prose without "
                    f"an INFERRED: marker; next cycle will treat it as evidence."
                )


def commit_rewrite(original_claims: list[dict], proposed_text: str, reexpandable_ids: set[str]) -> str:
    validate_rewrite(original_claims, proposed_text, reexpandable_ids)
    return proposed_text
