# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-provenance-weighted-memory-decay-when-a-re-write-resets-a-ttl-it-never-owned.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-provenance-weighted-memory-decay-when-a-re-write-resets-a-ttl-it-never-owned.warrant.json
# Markdown SHA-256:   688d15dddefd5993d5fa15bc8229a8e454c7897c6b8fb861ebadf5a84ec04767
# Code AST SHA-256:   516b10a3aa0e465f8fb3d129e2114eefe768932dbd56a0ee61701bf60b1d1253
# Verified Classes:   ProvenanceLaunderingError, Record, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write would reset decay or raise provenance without origin proof."""
    pass


@dataclass
class Record:
    record_id: str
    content: str
    origin_principal: str
    provenance: float
    expiry: float
    derivation_depth: int = 0
    derived_from: Optional[str] = None


@dataclass
class MemoryStore:
    records: dict = field(default_factory=dict)
    derivation_penalty: float = 0.85

    def write(self, record_id: str, content: str, principal: str,
              provenance: float, ttl: float, now: float,
              weakens_claim: bool = False) -> Record:
        existing = self.records.get(record_id)

        # No prior record: a fresh assertion. Provenance is whatever the
        # source claims; TTL is anchored to now.
        if existing is None:
            rec = Record(record_id, content, principal, provenance, now + ttl)
            self.records[record_id] = rec
            return rec

        is_refresh = (
            principal == existing.origin_principal
            and not weakens_claim
            and existing.derivation_depth == 0
        )

        if is_refresh:
            # Legitimate re-measure: reset clock, but provenance may only fall.
            existing.content = content
            existing.provenance = min(existing.provenance, provenance)
            existing.expiry = now + ttl
            return existing

        # Rewrite by a non-origin principal (or a weakening edit): FORK.
        # A rewrite must never extend the parent's lifetime or raise
        # provenance above the parent's. If the caller asked for either,
        # that is the laundering attempt and we refuse it.
        new_provenance = min(existing.provenance, provenance) * (
            self.derivation_penalty ** (existing.derivation_depth + 1)
        )
        new_expiry = min(existing.expiry, now + ttl)

        if new_expiry > existing.expiry:
            raise ProvenanceLaunderingError(
                f"write to {record_id!r} by {principal!r} would extend "
                f"expiry {existing.expiry}->{new_expiry} without origin proof"
            )
        if new_provenance > existing.provenance:
            raise ProvenanceLaunderingError(
                f"write to {record_id!r} by {principal!r} would raise "
                f"provenance {existing.provenance}->{new_provenance}"
            )

        fork_id = f"{record_id}#d{existing.derivation_depth + 1}"
        rec = Record(
            record_id=fork_id,
            content=content,
            origin_principal=principal,
            provenance=new_provenance,
            expiry=new_expiry,
            derivation_depth=existing.derivation_depth + 1,
            derived_from=record_id,
        )
        self.records[fork_id] = rec
        return rec

    def forget(self, threshold: float, now: float) -> list:
        dead = [rid for rid, r in self.records.items()
                if r.expiry <= now or r.provenance < threshold]
        for rid in dead:
            del self.records[rid]
        return dead
