# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-poisoning-detection-boundary-between-episodic-semantic-and-procedural-stores-when-the-same-corrupted-fact-propagates-a.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-poisoning-detection-boundary-between-episodic-semantic-and-procedural-stores-when-the-same-corrupted-fact-propagates-a.warrant.json
# Markdown SHA-256:   2c4dbc79993494fc9f5a16c6d368c18fe20e49a589b4871bc475e975e98cb452
# Code AST SHA-256:   58ec312b30c8a0e549e13766044b4b1e037b6695abf0cd1b8e33210bc2a4422f
# Verified Classes:   SourceClass, ProvenanceViolation, MemoryObject
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import FrozenSet


class SourceClass(IntEnum):
    # Higher = more trusted. Min-trust joins use the *lowest* member.
    EXTERNAL = 0
    INFERRED = 1
    INTERNAL = 2
    VERIFIED = 3


class ProvenanceViolation(RuntimeError):
    """Raised when a distillation edge would launder low-trust provenance
    into a higher-trust artifact, or when a procedure is compiled from
    unconfirmed facts."""


@dataclass(frozen=True)
class MemoryObject:
    content: str
    sources: FrozenSet[SourceClass]
    confirmed: bool = False

    @property
    def min_trust(self) -> SourceClass:
        if not self.sources:
            raise ProvenanceViolation("memory object has empty source set")
        return min(self.sources)


def merge_semantic(a: MemoryObject, b: MemoryObject) -> MemoryObject:
    """Min-trust join. Agreement between two low-trust sources must NOT
    raise trust or mark confirmed."""
    merged_sources = a.sources | b.sources
    # Confirmation requires an independent VERIFIED source, not mere agreement.
    confirmed = SourceClass.VERIFIED in merged_sources
    return MemoryObject(
        content=a.content,
        sources=merged_sources,
        confirmed=confirmed,
    )


def compile_procedural(fact: MemoryObject, trust_threshold: SourceClass) -> MemoryObject:
    """Compilation gate: refuse to emit a procedure whose min-trust source
    is below threshold or that is not confirmed."""
    if fact.min_trust < trust_threshold:
        raise ProvenanceViolation(
            f"refusing to compile procedure: min source class "
            f"{fact.min_trust.name} < threshold {trust_threshold.name}"
        )
    if not fact.confirmed:
        raise ProvenanceViolation(
            "refusing to compile procedure from unconfirmed semantic fact"
        )
    # Procedure must carry provenance forward, never strip it.
    return MemoryObject(
        content=f"PROCEDURE[{fact.content}]",
        sources=fact.sources,
        confirmed=True,
    )


# --- Reproduction of the observed failure path ---
if __name__ == "__main__":
    ep1 = MemoryObject("endpoint accepts unauthenticated writes",
                       frozenset({SourceClass.EXTERNAL}))
    ep2 = MemoryObject("endpoint accepts unauthenticated writes",
                       frozenset({SourceClass.EXTERNAL}))

    fact = merge_semantic(ep1, ep2)
    assert fact.min_trust == SourceClass.EXTERNAL
    assert not fact.confirmed  # correlated poisoning is not confirmation

    try:
        compile_procedural(fact, trust_threshold=SourceClass.INTERNAL)
    except ProvenanceViolation as e:
        print(f"BLOCKED: {e}")
    else:
        raise ProvenanceViolation("invariant breached: poison reached procedural store")
