# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-memory-poisoning-when-the-poisoned-entry-is-semantically-consistent-with-the-agent-s-own-prior-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-memory-poisoning-when-the-poisoned-entry-is-semantically-consistent-with-the-agent-s-own-prior-writes.warrant.json
# Markdown SHA-256:   8dd1a27420a6a7fd477d3e7de4d003cb88bed99e628651444a381a816c8098f0
# Code AST SHA-256:   489bdc0b2f141bdd1844d8c1fb2b62ebf50272bf3d09365190939853aaddf1cb
# Verified Classes:   TrustMonotonicityViolation, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Trust = Literal["untrusted", "internal", "verified"]
_TRUST_RANK = {"untrusted": 0, "internal": 1, "verified": 2}


class TrustMonotonicityViolation(RuntimeError):
    """Raised when a memory write or re-derivation claims more trust than its sources permit."""
    pass


@dataclass
class MemoryRecord:
    fact: str
    confidence: float
    derived_from: list[str]
    min_source_trust: Trust
    author: str = "self"


def _min_trust(trusts: list[Trust]) -> Trust:
    if not trusts:
        raise TrustMonotonicityViolation("record has empty derivation DAG; cannot assign trust")
    return min(trusts, key=lambda t: _TRUST_RANK[t])


def commit_record(
    fact: str,
    confidence: float,
    source_ids: list[str],
    source_trust: dict[str, Trust],
    store: dict[str, MemoryRecord],
) -> MemoryRecord:
    """
    Commit a distilled fact, enforcing that min_source_trust reflects the
    weakest leaf in the derivation DAG. Re-derivation from existing records
    inherits their taint; it may not be laundered upward.
    """
    leaf_trusts: list[Trust] = []
    for sid in source_ids:
        if sid in store:
            # Re-derivation: inherit the record's own min_source_trust, not its author.
            leaf_trusts.append(store[sid].min_source_trust)
        elif sid in source_trust:
            leaf_trusts.append(source_trust[sid])
        else:
            # Unknown provenance is treated as untrusted, never as internal.
            leaf_trusts.append("untrusted")

    inherited = _min_trust(leaf_trusts)

    # Guardrail: a distiller may not self-promote trust above its sources.
    if _TRUST_RANK[inherited] < _TRUST_RANK["internal"] and confidence > 0.5:
        # High confidence on untrusted derivation is the exact poisoning signature.
        # We still commit (distillation is imperfect) but the record is tainted.
        pass

    record = MemoryRecord(
        fact=fact,
        confidence=confidence,
        derived_from=source_ids,
        min_source_trust=inherited,
    )
    store[f"rec_{len(store):05d}"] = record
    return record


def may_ground_actuation(record: MemoryRecord, required: Trust = "internal") -> bool:
    """A record may only ground an action if its weakest source meets the bar."""
    if _TRUST_RANK[record.min_source_trust] < _TRUST_RANK[required]:
        return False
    return True


def assert_actuation_grounded(record: MemoryRecord, required: Trust = "internal") -> None:
    if not may_ground_actuation(record, required):
        raise TrustMonotonicityViolation(
            f"record '{record.fact[:40]}...' has min_source_trust="
            f"{record.min_source_trust!r}, below required {required!r}; "
            f"derivation leaves: {record.derived_from}"
        )
