# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-it-wrote-itself-write-time-validation-laundering-under-trust-tiered-retrieval-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-it-wrote-itself-write-time-validation-laundering-under-trust-tiered-retrieval-gating.warrant.json
# Markdown SHA-256:   2e3d15f34a49e408893d7473ba79f0d5cfe8f43319023cc335a1a426ad1417d1
# Code AST SHA-256:   3551fe562d2eda4affade6cf516a9496e7c1db02e0349ea6913e96881ed6853a
# Verified Classes:   TrustTier, MemoryLaunderingError, SourceEnvelope, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import IntEnum


class TrustTier(IntEnum):
    NEEDS_VERIFICATION = 0
    DERIVED = 1
    TOOL_VERIFIED = 2
    HUMAN_ATTESTED = 3


class MemoryLaunderingError(RuntimeError):
    """Raised when a write attempts to promote trust beyond what its provenance chain supports."""


@dataclass
class SourceEnvelope:
    raw_bytes: bytes
    root_source: str          # e.g. "tool:docparser@v3"
    is_derived_memory: bool   # True if source is another memory id, not an external event
    error_markers: list[str] = field(default_factory=list)  # truncation/uncertainty flags found in RAW bytes
    digest: str = ""

    def __post_init__(self):
        self.digest = hashlib.sha256(self.raw_bytes).hexdigest()


@dataclass
class MemoryRecord:
    claim: str
    envelope: SourceEnvelope
    admission: str = "pending"     # validator verdict — admission only
    trust_tier: TrustTier = TrustTier.NEEDS_VERIFICATION
    degraded: bool = False


def compute_trust_tier(env: SourceEnvelope, parent_tier: TrustTier | None) -> TrustTier:
    """Trust is a path property: root tier, minus one per derived hop, minus one if degraded."""
    if env.is_derived_memory:
        if parent_tier is None:
            raise MemoryLaunderingError(
                f"derived memory from {env.root_source} has no recorded parent tier; cannot certify provenance"
            )
        return TrustTier(max(TrustTier.NEEDS_VERIFICATION, parent_tier - 1))
    # root source
    root = TrustTier.TOOL_VERIFIED if env.root_source.startswith("tool:") else TrustTier.HUMAN_ATTESTED
    if env.error_markers:
        root = TrustTier(max(TrustTier.NEEDS_VERIFICATION, root - 1))
    return root


def admit_memory(
    claim: str,
    env: SourceEnvelope,
    validator_verdict: str,
    parent_tier: TrustTier | None = None,
) -> MemoryRecord:
    if validator_verdict != "passed":
        raise MemoryLaunderingError(f"admission rejected by validator: {validator_verdict}")

    degraded = bool(env.error_markers)
    tier = compute_trust_tier(env, parent_tier)

    # The laundering guard: a validator pass may never lift a memory above its provenance tier.
    requested_tier = TrustTier.TOOL_VERIFIED if env.root_source.startswith("tool:") else tier
    if requested_tier > tier:
        raise MemoryLaunderingError(
            f"promotion blocked: validator pass requested tier {requested_tier.name} "
            f"but provenance chain (degraded={degraded}, derived={env.is_derived_memory}) "
            f"supports only {tier.name}"
        )

    return MemoryRecord(
        claim=claim,
        envelope=env,
        admission="passed",
        trust_tier=tier,
        degraded=degraded,
    )


def verify_before_promotion(record: MemoryRecord, refetched_bytes: bytes) -> MemoryRecord:
    if hashlib.sha256(refetched_bytes).hexdigest() != record.envelope.digest:
        record.trust_tier = TrustTier.NEEDS_VERIFICATION
        record.degraded = True
        return record
    if record.envelope.error_markers:
        record.trust_tier = TrustTier.NEEDS_VERIFICATION
        record.degraded = True
    return record
