# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-its-own-memory-provenance-decay-collapse-when-a-poisoned-write-inherits-a-high-trust-author.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-its-own-memory-provenance-decay-collapse-when-a-poisoned-write-inherits-a-high-trust-author.warrant.json
# Markdown SHA-256:   13b754f8cf67c9d69988bc1cea7fe3701f9a6fd9a37e828b18132bfa97fc8e86
# Code AST SHA-256:   6e7557abcfc16ee36f2afc984da562b8bc05468cc445618a9c8f107ddcec8aef
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write's trust exceeds the weakest link in its lineage."""
    pass


def admit_write(entry, store, anomaly_sigma_threshold=2.5, trust_gate=0.7):
    # entry: dict with keys author, provenance_trust, content_anomaly_sigma, lineage
    # lineage: list of (author, trust) pairs that produced the current text, oldest first.
    # The current author is the last lineage member.
    if not entry["lineage"]:
        raise ProvenanceLaunderingError(
            f"entry authored by {entry['author']} has empty lineage; "
            "cannot verify trust bound"
        )

    weakest = min(t for _, t in entry["lineage"])
    if entry["provenance_trust"] > weakest + 1e-9:
        raise ProvenanceLaunderingError(
            f"trust {entry['provenance_trust']:.3f} exceeds lineage minimum "
            f"{weakest:.3f} for author {entry['author']}; "
            "content was transformed by a lower-trust principal"
        )

    # Anomaly must be scored on the text that will be retrieved (post-transform).
    if entry["content_anomaly_sigma"] >= anomaly_sigma_threshold:
        return {"admitted": False, "reason": "content_anomaly"}

    # AND-gate: both signals must independently clear their thresholds.
    if entry["provenance_trust"] < trust_gate:
        return {"admitted": False, "reason": "low_trust"}

    store.append(entry)
    return {"admitted": True, "effective_trust": weakest}


def consolidate(source_entry, new_text, summarizer_trust, summarizer_id,
                new_anomaly_sigma):
    # A transform extends lineage and can only lower the trust bound.
    lineage = list(source_entry["lineage"]) + [(summarizer_id, summarizer_trust)]
    return {
        "author": summarizer_id,
        "provenance_trust": min(t for _, t in lineage),  # lineage-min, never copied
        "content_anomaly_sigma": new_anomaly_sigma,      # scored on new_text
        "lineage": lineage,
    }
