# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-model-authored-context-rewrite-as-an-untrusted-patch-rather-than-a-trusted-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-model-authored-context-rewrite-as-an-untrusted-patch-rather-than-a-trusted-compaction.warrant.json
# Markdown SHA-256:   32d79c322040786cfe896124bf153f9a7a253c1517b3bd4ae9eafd85ea48b3e3
# Code AST SHA-256:   16a4d9e7c7e0b7326c7e9900d47c914f4c79a3382e054074c03dc99c46fc2987
# Verified Classes:   UntrustedRewriteError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UntrustedRewriteError(RuntimeError):
    """Raised when a model-authored context rewrite adds an assertion
    that is neither present in nor entailed by the pre-rewrite source."""
    pass


def validate_rewrite(source_assertions: set[str],
                     rewrite_ops: list[dict],
                     entailment_checker) -> list[str]:
    """
    source_assertions: atomic claims parsed from pre-rewrite context.
    rewrite_ops: [{"op": "assert"|"retract", "claim": str}, ...]
    entailment_checker: callable(claim, source_set) -> bool, run by a
        process independent of the rewriting model.

    Returns the list of accepted ops. Raises UntrustedRewriteError on
    the first unentailed addition. Never mutates source.
    """
    accepted = []
    for op in rewrite_ops:
        if op["op"] == "retract":
            # deletions are diff-detectable; accept if the claim existed
            if op["claim"] not in source_assertions:
                raise UntrustedRewriteError(
                    f"retract of non-existent claim: {op['claim']!r}"
                )
            accepted.append(op)
        elif op["op"] == "assert":
            claim = op["claim"]
            if claim in source_assertions:
                accepted.append(op)
                continue
            # the critical check: additions must be entailed, not merely new
            if not entailment_checker(claim, source_assertions):
                raise UntrustedRewriteError(
                    f"unentailed assertion in rewrite: {claim!r} "
                    f"not derivable from source; quarantined, "
                    f"source retained"
                )
            accepted.append(op)
        else:
            raise UntrustedRewriteError(f"unknown op: {op['op']!r}")
    return accepted


def apply_rewrite(source_context: str,
                  rewrite_ops: list[dict],
                  entailment_checker) -> str:
    source_assertions = parse_assertions(source_context)
    # validate against source BEFORE any mutation
    accepted = validate_rewrite(source_assertions, rewrite_ops,
                                entailment_checker)
    # source is retained by the caller; this returns a working copy only
    return render_ops(source_assertions, accepted)
