# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-taint-lineage-itself-was-written-by-the-poisoned-write-a-boundary-case-in-write-audit-chains-for.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-taint-lineage-itself-was-written-by-the-poisoned-write-a-boundary-case-in-write-audit-chains-for.warrant.json
# Markdown SHA-256:   f0d676fd8722880a96c5b327eb9b507ead1ba62861f0368e359e1bbba758ab55
# Code AST SHA-256:   59f900c8472ae69ed804e7929e421784b5e81797b821251e5803d465fe08b87d
# Verified Classes:   ProvenanceForgeryError, TraceEvent, StoreRecord, WriteAuditGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceForgeryError(RuntimeError):
    """Raised when a record's asserted lineage cannot be recomputed from the trace store."""
    pass


@dataclass
class TraceEvent:
    trace_id: str
    source_kind: str          # 'operator_config' | 'web_fetch' | 'peer_message' | 'tool_output'
    trust_class: str          # 'trusted' | 'untrusted'
    parent_content_hash: Optional[str] = None


@dataclass
class StoreRecord:
    record_id: str
    content: str
    trace_id: Optional[str]
    asserted_provenance: dict = field(default_factory=dict)  # agent-supplied; NEVER trusted


class WriteAuditGate:
    def __init__(self, trace_store: dict[str, TraceEvent], content_hashes: dict[str, str]):
        self.trace_store = trace_store
        self.content_hashes = content_hashes  # record_id -> sha256(content)

    def _recompute_taint(self, record: StoreRecord) -> str:
        # Lineage is resolved from the trace, not from asserted fields.
        if not record.trace_id or record.trace_id not in self.trace_store:
            # Fail closed: missing trace == untrusted.
            return "untrusted"
        ev = self.trace_store[record.trace_id]
        if ev.parent_content_hash is not None:
            # Recompute parent hash; a forged link fails here.
            actual = self.content_hashes.get(ev.parent_content_hash)
            if actual is None:
                raise ProvenanceForgeryError(
                    f"record {record.record_id}: parent_content_hash "
                    f"{ev.parent_content_hash!r} does not resolve to any stored content"
                )
            # Taint is monotone: derivative cannot be cleaner than parent.
            parent_taint = self.trace_store.get(
                self._trace_of(ev.parent_content_hash), TraceEvent("", "", "untrusted")
            ).trust_class
            if parent_taint == "untrusted":
                return "untrusted"
        return ev.trust_class

    def _trace_of(self, content_hash: str) -> str:
        for tid, ev in self.trace_store.items():
            if ev.parent_content_hash == content_hash:
                return tid
        return ""

    def admit(self, record: StoreRecord) -> bool:
        # Detect the forgery pattern: asserted-trusted but trace-resolved-untrusted.
        asserted = record.asserted_provenance.get("trust_class")
        recomputed = self._recompute_taint(record)
        if asserted == "trusted" and recomputed == "untrusted":
            raise ProvenanceForgeryError(
                f"record {record.record_id}: asserted trust_class=trusted but "
                f"trace {record.trace_id!r} recomputes to untrusted "
                f"(possible self-authored lineage)"
            )
        if recomputed == "untrusted":
            return False  # quarantine
        return True
