# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-memory-poisoning-when-its-audit-log-is-self-consistent-but-causally-incomplete.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-memory-poisoning-when-its-audit-log-is-self-consistent-but-causally-incomplete.warrant.json
# Markdown SHA-256:   6f8bb716a37c5b2205ebc3591357f76082574cdc048dc549ce5ed273491d0456
# Code AST SHA-256:   5ff7893992b972187be734e5c9f62f041fc1d95900d80b0a6a92ffa294d9e415
# Verified Classes:   IncompleteAuditError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class IncompleteAuditError(RuntimeError):
    """Raised when a log-internal audit is treated as store-completeness proof."""
    pass


def audit_memory_store(store: dict, journal: list, provenance: dict) -> None:
    """
    Regime B reconciliation. Raises IncompleteAuditError if the live store
    contains any key not produced by a journaled, provenance-carrying write.
    A clean log-internal replay is NOT sufficient.
    """
    # Step 1: replay the journal to reconstruct what the log claims the store is.
    replayed = {}
    for rec in journal:
        op = rec["op"]
        if op == "write":
            replayed[rec["key"]] = rec["value"]
        elif op == "forget":
            replayed.pop(rec["key"], None)
        elif op == "read":
            if rec["key"] not in replayed:
                raise IncompleteAuditError(
                    f"read of {rec['key']} with no prior write in journal"
                )

    # Step 2: reconcile live store against replay. Any key present live but
    # absent from replay is a write that bypassed the journal (C1 failure).
    live_keys = set(store.keys())
    replayed_keys = set(replayed.keys())
    unaccounted = live_keys - replayed_keys
    if unaccounted:
        raise IncompleteAuditError(
            f"store contains keys with no journaled write: {sorted(unaccounted)}"
        )

    # Step 3: provenance check. A complete log is not enough; each write must
    # carry a source on the allowlist (C3 failure otherwise).
    allowlist = {"user_input", "trusted_tool:retrieval_vetted", "agent:primary"}
    for key in live_keys:
        prov = provenance.get(key)
        if prov is None:
            raise IncompleteAuditError(
                f"key {key} has no provenance record; cannot certify origin"
            )
        if prov["source"] not in allowlist:
            raise IncompleteAuditError(
                f"key {key} written from untrusted source {prov['source']!r}"
            )

    # Only here is it sound to treat the store as audited.
    return None
