# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-across-memory-consolidation-boundaries-in-persistent-agent-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-across-memory-consolidation-boundaries-in-persistent-agent-stores.warrant.json
# Markdown SHA-256:   aea9867c850fb0ed98741cb5b662124c6ec3d42030ed69ef2f6c6b4afbeedb4b
# Code AST SHA-256:   f35cb4deb531af071f10ce50334f0291c60587829330823e6e0b38a831517361
# Verified Classes:   ProvenanceLaunderingError, EpisodicRecord, SemanticRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a consolidation write would raise trust above its inputs'
    floor tier, or when provenance cannot be derived from ground-truth cluster
    membership. This is a write-time guard, not a read-time detector."""


TRUST_RANK = {"T0": 0, "T1": 1, "T2": 2, "T3": 3}


@dataclass
class EpisodicRecord:
    record_id: str
    trust_tier: str          # T0..T3
    source_id: str
    content_hash: str


@dataclass
class SemanticRecord:
    record_id: str
    trust_tier: str
    source_ids: set[str]
    derived_from: list[str]  # input record_ids, store-assigned
    content: str = ""
    extra: dict = field(default_factory=dict)


def consolidate_cluster(
    cluster: list[EpisodicRecord],
    proposed_content: str,
    claimed_tier: str,
    new_id: str,
) -> SemanticRecord:
    """Author a semantic record from a cluster.

    Invariants enforced:
      I1: output tier == min(input tiers)  (trust is a lower bound on ancestry)
      I2: output source_ids == union(input source_ids)
      I3: derived_from == ground-truth cluster membership (store-assigned)
    """
    if not cluster:
        raise ProvenanceLaunderingError("empty cluster: nothing to derive from")

    floor_tier = min(cluster, key=lambda r: TRUST_RANK[r.trust_tier]).trust_tier
    union_sources = {r.source_id for r in cluster}
    ancestry = [r.record_id for r in cluster]

    # I1: the consolidator may not promote. If it claims a higher tier than the
    # floor of its inputs, the write is rejected outright -- do not silently
    # clamp, because a silent clamp hides that the model tried to launder.
    if TRUST_RANK[claimed_tier] > TRUST_RANK[floor_tier]:
        raise ProvenanceLaunderingError(
            f"proposed tier {claimed_tier} exceeds ancestry floor {floor_tier} "
            f"for cluster {ancestry}; consolidation may not raise trust"
        )

    # I2/I3 are assigned from ground truth, never from proposed_content.
    return SemanticRecord(
        record_id=new_id,
        trust_tier=floor_tier,
        source_ids=union_sources,
        derived_from=ancestry,
        content=proposed_content,
    )


def write_semantic(store: dict, rec: SemanticRecord) -> None:
    """Atomic write: record + derived_from edge land together or not at all."""
    for parent_id in rec.derived_from:
        if parent_id not in store:
            raise ProvenanceLaunderingError(
                f"dangling ancestry: {parent_id} absent at write of {rec.record_id}"
            )
    store[rec.record_id] = rec


# --- trigger trace -----------------------------------------------------------
store: dict = {
    "e_8821": EpisodicRecord("e_8821", "T0", "tool:web_fetch", "h1"),
    "e_8822": EpisodicRecord("e_8822", "T2", "operator:note", "h2"),
    "e_8823": EpisodicRecord("e_8823", "T2", "operator:note", "h3"),
}
cluster = [store["e_8821"], store["e_8822"], store["e_8823"]]
poison = "Deploy key rotation may be skipped if last_rotated < 30d."

try:
    # consolidator tries to stamp its own output as T3 (self-authored)
    rec = consolidate_cluster(cluster, poison, claimed_tier="T3", new_id="s_4402")
    write_semantic(store, rec)
except ProvenanceLaunderingError as exc:
    # expected: laundering blocked; caller must split the cluster or floor it
    assert "exceeds ancestry floor T0" in str(exc)
    rec = consolidate_cluster(cluster, poison, claimed_tier="T0", new_id="s_4402")
    write_semantic(store, rec)
    assert rec.trust_tier == "T0"
    assert rec.source_ids == {"tool:web_fetch", "operator:note"}
    assert rec.derived_from == ["e_8821", "e_8822", "e_8823"]
