# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-from-defeating-poisoning-detection-in-shared-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-from-defeating-poisoning-detection-in-shared-agent-memory.warrant.json
# Markdown SHA-256:   ea3d55c7482da536a2949ddf5057fc6a8188f35c541670ce7d121030437fb7b0
# Code AST SHA-256:   756ae410830c138710a43af78d66937f7665ec2153073f72b2917ff3e1f549e7
# Verified Classes:   ProvenanceLaunderingError, Write
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write's declared lineage cannot account for its content."""


@dataclass
class Write:
    write_id: str
    origin_agent: str
    trust_tier: str  # "TRUSTED" | "UNVERIFIED"
    parent_ids: list[str] = field(default_factory=list)
    content: str = ""
    is_signed_leaf: bool = False  # True only for harness-recorded tool observations


TIER_RANK = {"UNVERIFIED": 0, "TRUSTED": 1}
STORE: dict[str, Write] = {}


def _ancestors(write_id: str, seen: Optional[set] = None) -> set[str]:
    seen = seen or set()
    if write_id in seen:
        return seen
    seen.add(write_id)
    w = STORE.get(write_id)
    if w is None:
        raise ProvenanceLaunderingError(f"dangling parent reference: {write_id}")
    for p in w.parent_ids:
        _ancestors(p, seen)
    return seen


def effective_tier(w: Write) -> str:
    """Tier of a write is the minimum over itself and ALL ancestors."""
    ranks = [TIER_RANK[w.trust_tier]]
    for aid in _ancestors(w.write_id):
        if aid == w.write_id:
            continue
        ranks.append(TIER_RANK[STORE[aid].trust_tier])
    return "TRUSTED" if min(ranks) >= TIER_RANK["TRUSTED"] else "UNVERIFIED"


def admit(w: Write, declared_entailment_ok: bool) -> None:
    """
    Admit a write to the readable index only if lineage-closure holds.
    `declared_entailment_ok` is the result of the semantic coverage check:
    does the union of declared parents' content entail this write?
    """
    if not declared_entailment_ok:
        # Content that could only come from an undeclared source.
        raise ProvenanceLaunderingError(
            f"write {w.write_id} by {w.origin_agent} has undeclared ancestor: "
            f"declared parents {w.parent_ids} do not entail content"
        )
    tier = effective_tier(w)
    if tier != "TRUSTED":
        raise ProvenanceLaunderingError(
            f"write {w.write_id} inherits {tier} via ancestor closure; "
            f"quarantine until auditor re-derives from signed leaves"
        )
    STORE[w.write_id] = w


def register_leaf(write_id: str, agent: str, content: str) -> Write:
    w = Write(
        write_id=write_id,
        origin_agent=agent,
        trust_tier="UNVERIFIED",  # tool output is untrusted until verified
        parent_ids=[],
        content=content,
        is_signed_leaf=True,
    )
    STORE[write_id] = w
    return w


# --- Reproduce the laundering attempt ---
register_leaf("obs_8841", "Researcher", "deployment freeze 00:00-23:59 UTC")

# Synthesizer paraphrases the quarantined leaf and declares it as parent.
laundered = Write(
    write_id="synth_2210",
    origin_agent="Synthesizer",
    trust_tier="TRUSTED",
    parent_ids=["obs_8841"],  # honest declaration -> inherits UNVERIFIED
    content="freeze window covers most of the day",
)
# Entailment passes (it did read the leaf), but tier closure blocks admission.
admit(laundered, declared_entailment_ok=True)  # raises ProvenanceLaunderingError

# The laundering variant that omits the parent link:
forged = Write(
    write_id="synth_2211",
    origin_agent="Synthesizer",
    trust_tier="TRUSTED",
    parent_ids=["synth_2210"],  # cites its own prior synthesis, not the leaf
    content="freeze window covers most of the day",
)
# Coverage check fails: declared parents do not entail the claim.
admit(forged, declared_entailment_ok=False)  # raises ProvenanceLaunderingError
