# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-prior-writes-provenance-weighted-recall-and-trust-decay-at-the-self-authored-memory-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-prior-writes-provenance-weighted-recall-and-trust-decay-at-the-self-authored-memory-boundary.warrant.json
# Markdown SHA-256:   5e5e39d0b427ffe0e9cf7898c518cf51d1a26e8cd7450d15deb815dc9ec3ece4
# Code AST SHA-256:   7e6edab235ea1a862f5fd76a6b225cb75db43537cb9071995ce41c22590c9162
# Verified Classes:   TrustInvariantViolation, ProvenanceClass, Memory
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class TrustInvariantViolation(RuntimeError):
    """Raised when a memory's trust score changes for a reason not permitted by the invariant."""


class ProvenanceClass(Enum):
    EXTERNAL_VERIFIED = 3
    USER_ASSERTED = 2
    SELF_INFERENCE = 1
    SELF_SUMMARY = 0


# Provenance weight is a hard ceiling, not a multiplier that recency can rescue.
PROVENANCE_CEILING = {
    ProvenanceClass.EXTERNAL_VERIFIED: 1.0,
    ProvenanceClass.USER_ASSERTED: 0.85,
    ProvenanceClass.SELF_INFERENCE: 0.45,
    ProvenanceClass.SELF_SUMMARY: 0.30,
}

TAU_ACT = 0.70
TAU_REASON = 0.25
HALF_LIFE_SECONDS = 7 * 24 * 3600


def decay(age_seconds: float) -> float:
    return 0.5 ** (max(0.0, age_seconds) / HALF_LIFE_SECONDS)


@dataclass
class Memory:
    payload: str
    provenance: ProvenanceClass
    last_independent_confirmation: float
    derived_from: list["Memory"] = field(default_factory=list)
    _trust_cache: float | None = field(default=None, repr=False)

    def content_key(self) -> str:
        return hashlib.sha256(self.payload.encode("utf-8")).hexdigest()

    def effective_provenance(self) -> ProvenanceClass:
        # Summary cannot launder its sources: take the minimum over the derivation DAG.
        prov = self.provenance
        for parent in self.derived_from:
            parent_prov = parent.effective_provenance()
            if parent_prov.value < prov.value:
                prov = parent_prov
        return prov

    def trust(self, now: float) -> float:
        """Trust is a pure function of (provenance, time-since-independent-confirmation).

        It takes no argument derived from the read path. Calling this method must
        never mutate state that feeds back into it.
        """
        ceiling = PROVENANCE_CEILING[self.effective_provenance()]
        age = now - self.last_independent_confirmation
        score = ceiling * decay(age)
        if self._trust_cache is not None and abs(score - self._trust_cache) > 1e-12:
            # A change here is only legal if a confirmation event fired, which
            # mutates last_independent_confirmation and clears the cache.
            raise TrustInvariantViolation(
                f"trust drifted without a confirmation event for {self.content_key()[:12]}"
            )
        self._trust_cache = score
        return score

    def recall(self, now: float) -> float:
        """Retrieval path. Must be read-invariant: it returns trust and mutates nothing."""
        before = self.trust(now)
        # No writes to last_independent_confirmation, no cache invalidation.
        after = self.trust(now)
        if before != after:
            raise TrustInvariantViolation("recall mutated the trust function")
        return after

    def confirm(self, now: float, source: ProvenanceClass) -> None:
        """Corroboration path: the ONLY legal way to raise trust."""
        if source.value <= self.provenance.value:
            raise TrustInvariantViolation(
                "confirmation source must be strictly stronger than the memory's provenance"
            )
        self.provenance = source
        self.last_independent_confirmation = now
        self._trust_cache = None


def gate_for_action(memories: list[Memory], now: float) -> None:
    """Fail closed if any memory backing an irreversible action is self-authored or stale."""
    for m in memories:
        prov = m.effective_provenance()
        if prov not in (ProvenanceClass.EXTERNAL_VERIFIED, ProvenanceClass.USER_ASSERTED):
            raise TrustInvariantViolation(
                f"action blocked: memory {m.content_key()[:12]} has provenance "
                f"{prov.name}, which cannot clear tau_act regardless of recency"
            )
        if m.trust(now) < TAU_ACT:
            raise TrustInvariantViolation(
                f"action blocked: memory {m.content_key()[:12]} decayed below tau_act"
            )
