# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-write-that-passed-its-own-audit-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-write-that-passed-its-own-audit-chain.warrant.json
# Markdown SHA-256:   17f665c4ec0b908df2a009bba1f2f3af7cfe5406241ad27092c65493296c6594
# Code AST SHA-256:   42006c2408451bab8342f0420714a33cc389dc69df9f894cc536899a3e624d62
# Verified Classes:   TrustClass, ProvenanceLaunderingError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum

class TrustClass(Enum):
    EXTERNAL_USER = "external_user"      # user assertion / human approval
    SIGNED_TOOL = "signed_tool"          # tool result with verifiable origin
    UNTRUSTED_WEB = "untrusted_web"      # scraped / injected surface
    INTERNAL_DERIVED = "internal_derived" # distilled/summarized by our own agents

class ProvenanceLaunderingError(RuntimeError):
    pass

@dataclass
class MemoryRecord:
    seq: int
    parent_hash: str
    payload: str
    payload_hash: str
    signature: str
    trust_class: TrustClass
    source_ref: str | None  # must survive distillation; None = severed

def verify_chain(records: list[MemoryRecord]) -> bool:
    # integrity only: hashes, linkage, signatures. NOT truth.
    return all(r.payload_hash and r.signature for r in records)

IRREVERSIBLE_ACTIONS = {"rotate_credential", "delete_resource", "send_external"}

def promote_for_action(records: list[MemoryRecord], action: str) -> MemoryRecord:
    if not verify_chain(records):
        raise ProvenanceLaunderingError("chain integrity failed; refuse promotion")
    target = records[-1]

    if action in IRREVERSIBLE_ACTIONS:
        # chain validity is NECESSARY, not SUFFICIENT.
        if target.source_ref is None:
            raise ProvenanceLaunderingError(
                f"record seq={target.seq} drives irreversible '{action}' "
                f"but source edge was severed by distillation"
            )
        if target.trust_class in (TrustClass.UNTRUSTED_WEB, TrustClass.INTERNAL_DERIVED):
            raise ProvenanceLaunderingError(
                f"record seq={target.seq} drives irreversible '{action}' "
                f"from non-external trust class {target.trust_class.value}; "
                f"valid signature does not certify truth"
            )
    return target

# reproduces the observed failure if the guard above is removed:
poisoned = MemoryRecord(
    seq=42, parent_hash="a1b2", payload="api key rotates every 24h",
    payload_hash="deadbeef", signature="valid_sig_from_subagent",
    trust_class=TrustClass.UNTRUSTED_WEB, source_ref=None,  # severed by distillation
)
promote_for_action([poisoned], "rotate_credential")  # raises ProvenanceLaunderingError
