# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-memory-poisoning-during-cross-log-consistency-checks-on-agent-memory-operations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-memory-poisoning-during-cross-log-consistency-checks-on-agent-memory-operations.warrant.json
# Markdown SHA-256:   ff2ea3fff60bd98c4f6fd1686133d07556b5d2f135bce58e0eacdb2a7b2f6773
# Code AST SHA-256:   e2201e35f8be41df9b4e3a5d88cd366ca544e6c384507c2f926c7175ccca9695
# Verified Classes:   ProvenanceViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceViolation(RuntimeError):
    """Raised when a memory op log cannot be certified clean under provenance invariants."""
    pass


def check_write_admissible(op: dict, live_index: dict, producer_scopes: dict) -> None:
    key = op["key"]
    src = op.get("src")
    if not src or src not in producer_scopes:
        # Unresolvable source: not a rejection, but must be tagged unverified downstream.
        op["provenance"] = "unverified"
        return
    if key.split(":")[0] not in producer_scopes[src]:
        op["provenance"] = "unverified"
        return
    prior = live_index.get(key)
    if prior is not None and op.get("supersedes") != prior["op_id"]:
        raise ProvenanceViolation(
            f"write to {key!r} contradicts live op {prior['op_id']!r} "
            f"without supersede edge; source={src!r}"
        )
    op["provenance"] = "verified"


def certify_log(ops: list[dict], live_index: dict, producer_scopes: dict) -> str:
    for op in ops:
        if op["op"] == "write":
            check_write_admissible(op, live_index, producer_scopes)
        elif op["op"] == "forget":
            if op.get("target") not in live_index:
                raise ProvenanceViolation(
                    f"orphan forget: no live target {op.get('target')!r}"
                )
    if any(o.get("provenance") == "unverified" for o in ops if o["op"] == "write"):
        return "UNVERIFIED"
    return "CLEAN"
