# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-its-own-memory-rewrite-when-the-verifier-s-acceptance-signal-is-a-proxy-for-a-property-the-rewrite-can-counterfeit.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-its-own-memory-rewrite-when-the-verifier-s-acceptance-signal-is-a-proxy-for-a-property-the-rewrite-can-counterfeit.warrant.json
# Markdown SHA-256:   b66cc3da00d91fceb1059beb0df999ffa1450957c0352b2d4b897c05657e6c19
# Code AST SHA-256:   23de11cc94b3c495469b58dfb815e9f98da5018ff16190de8ea603c0606fd215
# Verified Classes:   ProvenanceMismatch, MemoryRewriteGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceMismatch(RuntimeError):
    """Raised when a subtractive memory rewrite cannot be justified by out-of-band evidence."""
    pass


class MemoryRewriteGuard:
    """
    Guards self-editing working memory. Subtractive rewrites (deletions, merges,
    closures, referent substitutions) must resolve their provenance tokens against
    the environment before submission. Additive rewrites pass through.
    """

    def __init__(self, witness):
        # witness.resolve(token) -> the actual bytes/record the token refers to.
        # The witness is out-of-band: the agent cannot write to it.
        self.witness = witness
        self.rejected_subgoals = set()

    def classify(self, rewrite):
        return "subtractive" if rewrite.removes_or_alters() else "additive"

    def submit(self, rewrite, subgoal_id):
        kind = self.classify(rewrite)

        if kind == "additive":
            return rewrite.apply()

        # Subtractive path: re-attempt after a rejection is itself a violation
        # unless new out-of-band evidence has arrived.
        if subgoal_id in self.rejected_subgoals and not rewrite.has_new_evidence():
            raise ProvenanceMismatch(
                f"subgoal {subgoal_id}: subtractive rewrite re-submitted after "
                f"rejection with no new out-of-band evidence; rejection is a "
                f"fact about the world, not a prompt to trim the buffer"
            )

        for entry in rewrite.affected_entries():
            token = entry.provenance_token
            if token is None:
                raise ProvenanceMismatch(
                    f"entry {entry.id}: subtractive rewrite of entry with no "
                    f"provenance token cannot be verified against the world"
                )
            resolved = self.witness.resolve(token)
            if resolved is None:
                raise ProvenanceMismatch(
                    f"entry {entry.id}: provenance token {token} does not resolve; "
                    f"cannot remove an entry whose source is unknown"
                )
            if not entry.assertion_matches(resolved):
                raise ProvenanceMismatch(
                    f"entry {entry.id}: token {token} resolves to content that "
                    f"contradicts the entry; deletion would launder a live "
                    f"contradiction, not resolve it"
                )

        self.rejected_subgoals.discard(subgoal_id)
        return rewrite.apply()

    def on_rejection(self, subgoal_id):
        # Record the rejection so a subsequent shrink-edit is caught.
        self.rejected_subgoals.add(subgoal_id)
