# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-verifies-memory-provenance-against-a-hash-chain-that-was-itself-written-by-a-poisoned-predecessor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-verifies-memory-provenance-against-a-hash-chain-that-was-itself-written-by-a-poisoned-predecessor.warrant.json
# Markdown SHA-256:   90392188f2ba878ae8662a79e92b09cd9e7c9f7440de48da06635a4ef3245eeb
# Code AST SHA-256:   da5cc3e8b231b3ea423a2cb88d2a8b970e3d10275e90590ff977ac5b4c5d8309
# Verified Classes:   TrustLevel, MemoryPoisoningError, MemoryEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class TrustLevel(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"
    DERIVED = "derived"


class MemoryPoisoningError(RuntimeError):
    """Raised when a chain-verified record fails provenance or authorization checks."""
    pass


@dataclass
class MemoryEntry:
    seq: int
    payload: dict
    provenance: TrustLevel
    writer_id: str
    prev_digest: str
    digest: str


def _recompute(entry: MemoryEntry) -> str:
    body = f"{entry.prev_digest}|{entry.seq}|{entry.provenance.value}|{entry.writer_id}|{entry.payload}"
    return hashlib.sha256(body.encode()).hexdigest()


def verify_chain(entries: list[MemoryEntry]) -> bool:
    """Continuity check only. True means no one edited history; it says nothing about safety."""
    prev = "GENESIS"
    for e in entries:
        if e.prev_digest != prev or e.digest != _recompute(e):
            return False
        prev = e.digest
    return True


def authorize_action(
    entry: MemoryEntry,
    action_risk: str,
    authorized_writers: dict[str, set[TrustLevel]],
) -> None:
    """Second gate: content provenance + writer authorization. Raises on violation."""
    if action_risk == "high" and entry.provenance is not TrustLevel.TRUSTED:
        raise MemoryPoisoningError(
            f"seq={entry.seq} provenance={entry.provenance.value} cannot drive high-risk action"
        )
    allowed = authorized_writers.get(entry.writer_id, set())
    if entry.provenance not in allowed:
        raise MemoryPoisoningError(
            f"writer={entry.writer_id} not authorized to assert provenance={entry.provenance.value}"
        )


def cold_start(
    entries: list[MemoryEntry],
    authorized_writers: dict[str, set[TrustLevel]],
) -> None:
    if not verify_chain(entries):
        raise MemoryPoisoningError("chain integrity broken — history was edited")
    # Chain is intact. Now re-check every entry before any downstream use.
    for e in entries:
        authorize_action(e, action_risk="high", authorized_writers=authorized_writers)
