# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-forgery-in-its-own-memory-store-when-a-poisoned-episodic-record-inherits-the-trust-score-of-the-legitimate-reco.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-forgery-in-its-own-memory-store-when-a-poisoned-episodic-record-inherits-the-trust-score-of-the-legitimate-reco.warrant.json
# Markdown SHA-256:   9149a621e76b673786a3a17891e3d32859c03bd434212bb3954e7948c406af53
# Code AST SHA-256:   c643492f59a112dfb1bb44b180edf004171b70ddfc9d7eeb91b32fd03e0128a8
# Verified Classes:   ProvenanceInconsistency, Envelope, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceInconsistency(RuntimeError):
    """Raised when a record's stored trust exceeds the lower bound implied by its sealed derivation set."""
    pass


@dataclass(frozen=True)
class Envelope:
    source_agent: str
    source_trust: float          # 0.0 .. 1.0
    signature: str               # covers payload_hash + derivation hashes


@dataclass
class MemoryRecord:
    slot: str
    payload_hash: str
    envelope: Envelope
    stored_trust: float
    derivation: tuple[str, ...] = field(default_factory=tuple)  # content hashes of constituent records


def recompute_trust_bound(record: MemoryRecord, envelope_index: dict[str, Envelope]) -> float:
    if not record.derivation:
        # Leaf record: trust is its own source trust, nothing inherited.
        return record.envelope.source_trust
    missing = [h for h in record.derivation if h not in envelope_index]
    if missing:
        raise ProvenanceInconsistency(
            f"record at slot {record.slot} declares derivation hashes {missing} "
            f"with no sealed envelope; cannot establish trust lower bound"
        )
    return min(envelope_index[h].source_trust for h in record.derivation)


def score_for_retrieval(
    record: MemoryRecord,
    envelope_index: dict[str, Envelope],
    epsilon: float = 1e-6,
) -> float:
    bound = recompute_trust_bound(record, envelope_index)
    if record.stored_trust > bound + epsilon:
        raise ProvenanceInconsistency(
            f"slot {record.slot}: stored_trust={record.stored_trust:.3f} exceeds "
            f"derivation lower bound={bound:.3f} (delta={record.stored_trust - bound:.3f}); "
            f"payload {record.payload_hash[:12]} inherited trust it did not earn"
        )
    return min(record.stored_trust, bound)


def seal_distillation(summary_payload: bytes, inputs: list[MemoryRecord]) -> tuple[str, tuple[str, ...]]:
    payload_hash = hashlib.sha256(summary_payload).hexdigest()
    derivation = tuple(r.payload_hash for r in inputs)
    return payload_hash, derivation
