# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-roll-back-memory-poisoning-when-its-signed-journal-attests-to-writes-it-cannot-semantically-trust.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-roll-back-memory-poisoning-when-its-signed-journal-attests-to-writes-it-cannot-semantically-trust.warrant.json
# Markdown SHA-256:   2fc501ab76061c248796eb1ae6900ea3f91bdf9dfae8e57c29f95fc5e6531153
# Code AST SHA-256:   8f83baa5be98b411548a86967c0ca61a53d222760a2a57c8153b766ed4d266d5
# Verified Classes:   SourceClass, ClaimKind, MemoryPoisoningError, JournalEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class SourceClass(str, Enum):
    OPERATOR = "operator_instruction"
    TRUSTED_CONFIG = "trusted_config"
    AGENT_INFERENCE = "agent_inference"
    UNTRUSTED_TOOL = "untrusted_tool_output"
    PEER_AGENT = "peer_agent_message"


class ClaimKind(str, Enum):
    OBSERVATION = "observation"
    POLICY = "policy"
    CAPABILITY = "capability"
    IDENTITY = "identity"


UNTRUSTED = {SourceClass.UNTRUSTED_TOOL, SourceClass.PEER_AGENT}
PRIVILEGED_CLAIMS = {ClaimKind.POLICY, ClaimKind.CAPABILITY, ClaimKind.IDENTITY}


class MemoryPoisoningError(RuntimeError):
    """Raised when a signed journal entry cannot be trusted for load."""


@dataclass(frozen=True)
class JournalEntry:
    seq: int
    source_class: SourceClass
    claim_kind: ClaimKind
    derivation: tuple[int, ...]
    signature_valid: bool = True  # integrity already verified upstream


def assert_loadable(entry: JournalEntry) -> None:
    """Structural gate: signature validity is necessary, not sufficient."""
    if not entry.signature_valid:
        # This is the *easy* case; the chain check already caught it.
        raise MemoryPoisoningError(
            f"seq={entry.seq}: signature invalid, reject outright"
        )
    if entry.claim_kind in PRIVILEGED_CLAIMS and entry.source_class in UNTRUSTED:
        # The hard case: authenticated poison. Signature is fine; content is not.
        raise MemoryPoisoningError(
            f"seq={entry.seq}: {entry.claim_kind.value} claim from "
            f"{entry.source_class.value} is structurally forbidden"
        )


def derivation_closure(
    suspect_seq: int, journal: Iterable[JournalEntry]
) -> set[int]:
    """All entries that transitively derive from the suspect entry."""
    by_seq = {e.seq: e for e in journal}
    closure: set[int] = set()
    frontier = [suspect_seq]
    while frontier:
        cur = frontier.pop()
        for e in by_seq.values():
            if cur in e.derivation and e.seq not in closure:
                closure.add(e.seq)
                frontier.append(e.seq)
    return closure


def quarantine_and_plan_rollback(
    suspect: JournalEntry, journal: list[JournalEntry], budget_ok: bool
) -> list[int]:
    """Return the sequence set to tombstone; fail closed if rebuild is too costly."""
    assert_loadable(suspect)  # raises if the entry is structurally poisoned
    closure = derivation_closure(suspect.seq, journal)
    if closure and not budget_ok:
        # Partial rebuild would silently drop derivation edges -> next poison slips.
        raise MemoryPoisoningError(
            f"seq={suspect.seq}: derivation closure {sorted(closure)} "
            f"exceeds rebuild budget; refusing to resume on partial store"
        )
    return [suspect.seq, *sorted(closure)]
