# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-its-own-provenance-check-already-flagged-the-source-as-untrusted.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-its-own-provenance-check-already-flagged-the-source-as-untrusted.warrant.json
# Markdown SHA-256:   a05c918a5ba81602543f7654d880a51e1e42116272dbd27820521b35ec7ad0e5
# Code AST SHA-256:   dca6a48736ae1f8889b70c3415bc738e162ced9fcb02e49cbaadda30bde15885
# Verified Classes:   ProvenanceAdmissionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

if record.trust_tier_rank >= store.min_admit_rank:
    store.write(record)   # min_admit_rank was set to 'external' for
                          # tool-summary ingestion, to allow bulk ingest

class ProvenanceAdmissionError(RuntimeError):
    """Raised when a memory write's admission path bypasses its trust verdict."""
    pass


TIER_RANK = {"external": 0, "peer": 1, "verified": 2}


def admit_memory_write(record, store, ingest_mode):
    """
    Two-key admission: trust-gate action AND content-gate contradiction check.
    A rank comparison alone is not admission; it is a defect.
    """
    trust = record.provenance_check  # {"trust_gate": ..., "recommended_action": ...}

    # Key 1: the trust gate's ACTION, not its rank, gates admission.
    if trust["recommended_action"] == "quarantine":
        if ingest_mode == "bulk_external":
            # Quarantine is mandatory for bulk external ingest.
            store.quarantine(record)
            return "quarantined"
        raise ProvenanceAdmissionError(
            f"trust gate returned quarantine for {record.source_agent} "
            f"but admission path attempted to write under mode={ingest_mode}"
        )

    # Key 2: contradiction check scoped to ALL tiers >= the write's own tier.
    write_rank = TIER_RANK[record.trust_tier]
    for existing in store.iter_records():
        if TIER_RANK[existing.trust_tier] < write_rank:
            continue  # lower-tier records cannot veto a higher-tier write
        if existing.contradicts(record.claim):
            if record.trust_tier == "external" and existing.trust_tier == "verified":
                # Corroboration with a verified record is the one external admit path.
                if existing.corroborates(record.claim):
                    store.write(record)
                    return "admitted_corroborated"
            store.quarantine(record)
            return "quarantined_contradiction"

    store.write(record)
    return "admitted"


def retrieve(memory, query, require_label_conditioning=True):
    """Retrieval must condition on trust label for admitted-with-label records."""
    hits = memory.rank(query)
    for hit in hits:
        if hit.trust_tier == "external" and require_label_conditioning:
            if not hit.consumer_conditions_on_label:
                raise ProvenanceAdmissionError(
                    f"external record {hit.id} surfaced to consumer that does not "
                    f"condition on its UNVERIFIED label; retrieval contract violated"
                )
    return hits
