# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-poisoned-memory-without-auditing-the-forget-tool-s-write-path-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-poisoned-memory-without-auditing-the-forget-tool-s-write-path-provenance.warrant.json
# Markdown SHA-256:   5e222e03ff9dbb49df0795326bd810a838e446c2b59493c163b181c2e4a72971
# Code AST SHA-256:   cdc8baa5235639c6bcdcd9e334219d443ebf66287a8f93c019d62570756d3e6e
# Verified Classes:   UnprovenancedForgetError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnprovenancedForgetError(RuntimeError):
    """Raised when a forget request lacks principal provenance or pre-image capture."""
    pass


ALLOWLISTED_PRINCIPALS = {"user:alice", "orchestrator:signed", "policy:engine"}


def forget_entry(store, audit_sink, key, requester_principal, motivation_source):
    # Invariant: requester authority must be independent of retrieved content.
    if requester_principal not in ALLOWLISTED_PRINCIPALS:
        raise UnprovenancedForgetError(
            f"forget({key!r}) from {requester_principal!r} not an authenticated principal"
        )
    if motivation_source.startswith("retrieved:"):
        raise UnprovenancedForgetError(
            f"forget({key!r}) motivated by untrusted content {motivation_source!r}; "
            "deletion authority cannot derive from retrieved text"
        )

    pre_image = store.get(key)
    if pre_image is None:
        return False  # idempotent miss, nothing to audit

    # Write-ahead audit: pre-image must be durable before deletion commits.
    audit_sink.append({
        "op": "forget",
        "key": key,
        "prior_value": pre_image.value,
        "prior_provenance": pre_image.provenance,
        "requester": requester_principal,
        "motivation": motivation_source,
    })
    if not audit_sink.flushed():
        raise UnprovenancedForgetError(
            f"audit sink not durable; refusing to commit forget({key!r})"
        )

    store.delete(key)
    return True
