# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-provenance-laundering-attack-evades-memory-poisoning-defenses-in-persistent-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-provenance-laundering-attack-evades-memory-poisoning-defenses-in-persistent-agent-memory.warrant.json
# Markdown SHA-256:   3873ea77282d6d76c04bf3a8290b59219c1b5c408cbbf952347679a97d73adbc
# Code AST SHA-256:   16c38c54a15eaaa6159cca18a71dce8f505b61ddbec20b64988759310787fae6
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory record's trust tier exceeds the minimum
    tier of its derivation set, or when derivation edges are missing."""
    pass


TIER_RANK = {"UNTRUSTED": 0, "TOOL": 1, "PEER": 2, "SELF": 3}


def stamp_derived_record(record, derivation_set):
    """Write-path guard: a memory-to-memory transformation must inherit the
    minimum tier of its inputs and must persist every derivation edge."""
    if not derivation_set:
        raise ProvenanceLaunderingError(
            f"record {record['id']} claims derivation but has empty input set"
        )

    min_tier = min(TIER_RANK[i["tier"]] for i in derivation_set)
    claimed = TIER_RANK[record["tier"]]

    if claimed > min_tier:
        raise ProvenanceLaunderingError(
            f"record {record['id']} stamped {record['tier']} but derivation-set "
            f"minimum is {min_tier}: trust monotonicity violated"
        )

    missing = [i["id"] for i in derivation_set if i["id"] not in record["derivation"]]
    if missing:
        raise ProvenanceLaunderingError(
            f"record {record['id']} dropped derivation edges to {missing}"
        )

    return record


def audit_retrieval(hit, memory_graph):
    """Retrieval backstop: reject a high-trust hit if any ancestor in its
    derivation graph is lower-trust than the hit itself."""
    hit_rank = TIER_RANK[hit["tier"]]
    stack = list(hit["derivation"])
    seen = set()

    while stack:
        node_id = stack.pop()
        if node_id in seen:
            continue
        seen.add(node_id)
        node = memory_graph[node_id]
        if TIER_RANK[node["tier"]] < hit_rank:
            raise ProvenanceLaunderingError(
                f"retrieved {hit['id']} at {hit['tier']} has low-trust ancestor "
                f"{node_id} at {node['tier']}: provenance-laundered record admitted"
            )
        stack.extend(node.get("derivation", []))

    return hit
