# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-memory-write-it-cannot-re-derive-write-audit-differential-consistency-and-the-silent-poisoning-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-memory-write-it-cannot-re-derive-write-audit-differential-consistency-and-the-silent-poisoning-window.warrant.json
# Markdown SHA-256:   c4ad256d27c347eb10c3a46f49310e8c935a2ea3847ca697dab627c079b76664
# Code AST SHA-256:   dba6c9b90667c5281cb88a4a2e21cc9a0b5d0e987e6b683c87a97b0943649e9a
# Verified Classes:   AuditIndependenceViolation, Span, Derivation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AuditIndependenceViolation(RuntimeError):
    """Raised when an auditor's derivation cannot be admitted as independent evidence."""


@dataclass(frozen=True)
class Span:
    start: int
    end: int

    def superset_of(self, other: "Span") -> bool:
        return self.start <= other.start and self.end >= other.end


@dataclass(frozen=True)
class Derivation:
    claim_object: str
    read_span: Span
    injection_score: float


def admit_write(
    writer_claim: str,
    cited_span: Span,
    auditor: Derivation,
    injection_threshold: float = 0.5,
) -> str:
    """
    Returns one of: 'COMMIT', 'INCONCLUSIVE', 'POISONING'.
    Never reconciles by majority; never treats equality under partial
    coverage as a pass.
    """
    if not auditor.read_span.superset_of(cited_span):
        # Equality here is evidence of shared truncation, not correctness.
        return "INCONCLUSIVE"

    if auditor.injection_score >= injection_threshold:
        raise AuditIndependenceViolation(
            f"auditor read injection-laden slice "
            f"(score={auditor.injection_score:.2f}, span={auditor.read_span}); "
            f"derivation is not independent evidence"
        )

    if auditor.claim_object != writer_claim:
        return "POISONING"

    return "COMMIT"


def consolidate(memories: list[dict]) -> list[dict]:
    committed = []
    for m in memories:
        verdict = admit_write(
            writer_claim=m["claim"],
            cited_span=m["span"],
            auditor=m["auditor"],
        )
        if verdict == "COMMIT":
            committed.append({**m, "provenance_confidence": True})
        elif verdict == "POISONING":
            raise AuditIndependenceViolation(
                f"poisoning detected on {m['subject']}.{m['predicate']}: "
                f"writer={m['claim']!r} auditor={m['auditor'].claim_object!r}"
            )
        # INCONCLUSIVE: re-audit with expanded budget; do not commit, do not vote.
    return committed
