# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-in-a-decay-weighted-memory-write-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-in-a-decay-weighted-memory-write-schema.warrant.json
# Markdown SHA-256:   19ab95c63318572d2f241b28e95b81f8125fd54f9626f6a7ee65519bf711da00
# Code AST SHA-256:   7efa18f19db22d05c087d933979474255166aaddc1e089a0977392112774d512
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field

SOURCE_RANK = {"inference": 0, "paraphrase": 1, "observation": 2, "tool_result": 3}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write upgrades provenance without new external evidence."""


@dataclass
class MemoryEntry:
    key: str
    value: object
    source: str
    confidence: float
    derived_from: list[str]
    t_last_external_observation: float
    access_count: int = 0


@dataclass
class MemoryStore:
    entries: dict[str, MemoryEntry] = field(default_factory=dict)
    external_artifacts: set[str] = field(default_factory=set)

    def _has_external_leaf(self, derived_from: list[str]) -> bool:
        return any(ref in self.external_artifacts for ref in derived_from)

    def write(self, key, value, source, confidence, derived_from):
        existing = self.entries.get(key)
        if existing is None:
            if source in ("observation", "tool_result") and not self._has_external_leaf(derived_from):
                raise ProvenanceLaunderingError(
                    f"new key {key!r} claims source={source!r} "
                    f"but derived_from={derived_from!r} has no external leaf"
                )
            self.entries[key] = MemoryEntry(
                key, value, source, confidence, list(derived_from), time.time()
            )
            return

        # Existing key: enforce monotonic provenance.
        upgraded = SOURCE_RANK[source] > SOURCE_RANK[existing.source]
        confidence_raised = confidence > existing.confidence
        new_evidence = self._has_external_leaf(derived_from) and any(
            ref not in existing.derived_from for ref in derived_from
        )

        if (upgraded or confidence_raised) and not new_evidence:
            raise ProvenanceLaunderingError(
                f"write to {key!r} upgrades source {existing.source!r}->{source!r} "
                f"or confidence {existing.confidence}->{confidence} "
                f"with derived_from={derived_from!r}; no new external artifact cited"
            )

        if new_evidence:
            existing.source = source
            existing.confidence = confidence
            existing.derived_from = list(derived_from)
            existing.t_last_external_observation = time.time()
        else:
            # Self-referential restatement: preserve strength, do not reset decay clock.
            existing.confidence = min(existing.confidence, confidence)
            existing.derived_from = list(dict.fromkeys(existing.derived_from + derived_from))
            existing.access_count += 1
        existing.value = value

    def audit(self):
        for entry in self.entries.values():
            if entry.source in ("observation", "tool_result") and not self._has_external_leaf(
                entry.derived_from
            ):
                raise ProvenanceLaunderingError(
                    f"audit: {entry.key!r} carries source={entry.source!r} "
                    f"but its provenance DAG has no external leaf: {entry.derived_from!r}"
                )
