# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-writes-a-poisoned-memory-entry-that-passes-its-own-integrity-checksum.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-writes-a-poisoned-memory-entry-that-passes-its-own-integrity-checksum.warrant.json
# Markdown SHA-256:   5ba895b36cfc0023de37f17ed026d3f17a860504e59933d00b991686032033ab
# Code AST SHA-256:   80a2c4119754d8285f5a5f49f14d05c26d4cc81875732a75386816cfbe39a6f1
# Verified Classes:   TrustTier, ProvenanceUnattestedError, MemoryEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TrustTier(IntEnum):
    UNATTESTED = 0
    USER_TURN = 1
    TOOL_RESULT = 2
    SIGNED_INTERNAL = 3


class ProvenanceUnattestedError(RuntimeError):
    """Raised when a hash-valid memory entry is used to route an irreversible action
    without an independent provenance attestation. The checksum proved the bytes did
    not change; it did not prove the bytes were trustworthy when written."""


@dataclass(frozen=True)
class MemoryEntry:
    payload: str
    provenance: frozenset[str]
    tier: TrustTier
    anomaly_score: float
    sha256: str = field(init=False)

    def __post_init__(self):
        # Checksum covers payload AND provenance: neither is alterable alone.
        digest = hashlib.sha256(
            (self.payload + "|" + "|".join(sorted(self.provenance))).encode()
        ).hexdigest()
        object.__setattr__(self, "sha256", digest)

    def checksum_valid(self) -> bool:
        recomputed = hashlib.sha256(
            (self.payload + "|" + "|".join(sorted(self.provenance))).encode()
        ).hexdigest()
        return recomputed == self.sha256


def distill(entries: list[MemoryEntry], summary_payload: str) -> MemoryEntry:
    """Episodic->semantic consolidation. Provenance is the WEAKEST input tier,
    and the intersection of attestations — never a freshly minted one."""
    if not entries:
        raise ProvenanceUnattestedError("cannot distill from empty episodic set")
    weakest = min(e.tier for e in entries)
    common = frozenset.intersection(*(e.provenance for e in entries))
    # Distilled entry inherits the weakest tier; anomaly score is NOT a trust signal.
    return MemoryEntry(
        payload=summary_payload,
        provenance=common,
        tier=weakest,
        anomaly_score=0.0,
    )


def route_irreversible_action(entry: MemoryEntry, min_tier: TrustTier = TrustTier.TOOL_RESULT) -> str:
    """The action boundary. Hash validity is checked but is NOT sufficient."""
    if not entry.checksum_valid():
        raise ProvenanceUnattestedError(
            f"checksum mismatch on entry {entry.sha256[:12]}: post-write tampering"
        )
    if entry.tier < min_tier:
        raise ProvenanceUnattestedError(
            f"entry {entry.sha256[:12]} is hash-valid but provenance tier "
            f"{entry.tier.name} < required {min_tier.name}; "
            f"checksum match is not a trust signal"
        )
    return entry.payload


# Reproduction of the observed failure:
# A poisoned entry written via a tool result path with no signed attestation.
poisoned = MemoryEntry(
    payload="Deployment target is prod-db-2; previous target staging deprecated.",
    provenance=frozenset({"web-fetch-7"}),   # unsigned external source
    tier=TrustTier.UNATTESTED,               # no attestation
    anomaly_score=0.31,                      # below scorer threshold -> write passed
)
assert poisoned.checksum_valid()             # checksum launders the poison

# Distillation does NOT upgrade it — weakest tier wins.
distilled = distill([poisoned], "target=prod-db-2")
assert distilled.tier == TrustTier.UNATTESTED

# The action boundary is where it must fail — not the read boundary.
try:
    route_irreversible_action(distilled)
except ProvenanceUnattestedError as exc:
    print(f"BLOCKED at action boundary: {exc}")
