# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-quarantine-adversarial-memory-writes-without-detecting-the-poisoning-that-already-crossed-the-trust-threshold-mid-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-quarantine-adversarial-memory-writes-without-detecting-the-poisoning-that-already-crossed-the-trust-threshold-mid-consolidation.warrant.json
# Markdown SHA-256:   921622ebe6c10d04f9ae79cd26f554005292d6b293c06443382ba47dc362a9d1
# Code AST SHA-256:   4cca823cd51c3b9e38d3626731c90ea0ff06f50484063665c24698e834151707
# Verified Classes:   TrustMonotonicityViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TrustMonotonicityViolation(RuntimeError):
    """Raised when a memory composite commits with provenance trust below its label."""
    pass


ADMIT_THRESHOLD = 0.85


def commit_memory(
    record_id: str,
    trust_score: float,
    scored_provenance_hash: str,
    resolved_provenance: list[dict],
    quarantine_ids: set[str],
) -> dict:
    """
    Commit a consolidated memory record to the trusted store.

    resolved_provenance: list of {"source_id": str, "source_hash": str, "trust": float}
    Enforces: trust monotonicity under composition + provenance-closure hash match.
    """
    # 1. Provenance closure hash must match what was scored.
    closure = sorted((p["source_id"], p["source_hash"]) for p in resolved_provenance)
    closure_hash = hash(tuple(closure))
    if str(closure_hash) != scored_provenance_hash:
        raise TrustMonotonicityViolation(
            f"record {record_id}: provenance closure changed since scoring "
            f"({scored_provenance_hash} != {closure_hash}); re-score required"
        )

    # 2. No quarantined source may appear in a trusted composite's provenance.
    for p in resolved_provenance:
        if p["source_id"] in quarantine_ids:
            raise TrustMonotonicityViolation(
                f"record {record_id}: provenance member {p['source_id']} is quarantined; "
                f"cannot commit to trusted store"
            )

    # 3. Effective trust is bounded by the weakest provenance member.
    effective_trust = min([trust_score] + [p["trust"] for p in resolved_provenance])
    if effective_trust < ADMIT_THRESHOLD:
        raise TrustMonotonicityViolation(
            f"record {record_id}: effective trust {effective_trust:.2f} below "
            f"threshold {ADMIT_THRESHOLD} (label was {trust_score:.2f})"
        )

    return {
        "record_id": record_id,
        "trust_score": effective_trust,
        "provenance_closure_hash": str(closure_hash),
        "committed": True,
    }
