# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-memory-write-whose-provenance-chain-is-internally-consistent-but-whose-originating-agent-was-itself-compromised-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-memory-write-whose-provenance-chain-is-internally-consistent-but-whose-originating-agent-was-itself-compromised-mid.warrant.json
# Markdown SHA-256:   4a9dfd9417fd3c873f95c2747c4dec8c33ee534173486227bea0ed87f17cf115
# Code AST SHA-256:   299c22bfc47ca9ed513682786e1828c8533959ebbbb5758cd6144936b62e1a62
# Verified Classes:   ProvenanceConsistencyIsNotTrustError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ProvenanceConsistencyIsNotTrustError(RuntimeError):
    """Raised when a write passes provenance-consistency auditing but its
    origin leaf was never re-derived independently, so consistency proves
    faithful relay of a possibly-poisoned leaf rather than trustworthy content."""
    pass


UNTRUSTED_LEAF_KINDS = {"external_document", "tool_return", "inbound_message", "retrieved_memory"}


def admit_memory_write(write, provenance_graph, auditor) -> bool:
    """
    Decide whether a provenance-consistent write may be admitted to long-term store.
    `write` carries: writer_id, parent_write_ids, source_refs, session_nonce, content_hash.
    `provenance_graph` resolves parents and leaves.
    `auditor` exposes: rederive(leaf) -> content_hash | None, and
                       did_consume(session_nonce, suspect_write_id) -> bool.
    """
    # Step 1: the existing consistency audit. Necessary, not sufficient.
    chain = provenance_graph.walk_to_leaves(write)
    for hop in chain.hops:
        if not provenance_graph.parent_resolves(hop.parent_write_id):
            raise ProvenanceConsistencyIsNotTrustError(
                f"provenance inconsistency at hop {hop.parent_write_id}: broken parent link"
            )
        if hop.content_hash != provenance_graph.declared_hash(hop.parent_write_id):
            raise ProvenanceConsistencyIsNotTrustError(
                f"provenance inconsistency at hop {hop.parent_write_id}: hash mismatch"
            )
    # At this point the chain is internally consistent. The naive auditor stops here.

    # Step 2: derivation-integrity check. The chain being consistent says nothing
    # about whether the origin leaf was faithfully interpreted.
    for leaf in chain.leaves:
        if leaf.kind in UNTRUSTED_LEAF_KINDS:
            rederived = auditor.rederive(leaf)
            if rederived is None:
                # Cannot independently re-derive: must taint, not admit.
                raise ProvenanceConsistencyIsNotTrustError(
                    f"origin leaf {leaf.ref} is untrusted-input and not re-derivable; "
                    f"consistent provenance proves faithful relay, not trustworthy content"
                )
            if rederived != leaf.content_hash:
                raise ProvenanceConsistencyIsNotTrustError(
                    f"origin leaf {leaf.ref} failed independent re-derivation: "
                    f"derived {leaf.content_hash} != re-derived {rederived}"
                )

    # Step 3: corroboration-independence check. Agreement among descendants of the
    # same suspect write is the same poison counted twice, not independent evidence.
    corroborators = [w for w in provenance_graph.writes_confirming(write)
                     if w.writer_id != write.writer_id]
    for c in corroborators:
        if auditor.did_consume(c.session_nonce, write.id):
            raise ProvenanceConsistencyIsNotTrustError(
                f"corroborator {c.writer_id} descends from suspect write {write.id}; "
                f"agreement is not topologically independent"
            )

    # Step 4: session-integrity check. A session mutated mid-flight cannot vouch
    # for a write it produced after the mutation, regardless of clean provenance.
    if auditor.session_mutated_before(write.session_nonce, write.id):
        raise ProvenanceConsistencyIsNotTrustError(
            f"writer session {write.session_nonce} was mutated before write {write.id}; "
            f"origin cannot self-attest"
        )

    return True
