# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-provenance-tracked-writes-and-anomaly-scored-recall-disagree-at-the-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-provenance-tracked-writes-and-anomaly-scored-recall-disagree-at-the-trust-boundary.warrant.json
# Markdown SHA-256:   1de9d87b9d40dff1aff7057996dbb6de7c00b7690c40ef248d73c801e72163ef
# Code AST SHA-256:   98935181284cd562ba9f25cfbe47afbd9f1203503f2f63de208c11c6053e6354
# Verified Classes:   ProvenanceIncompleteError, TrustBoundaryViolation, Resolution, RecallCandidate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ProvenanceIncompleteError(RuntimeError):
    """Provenance is point-to-point; cannot support the agreement invariant."""
    pass


class TrustBoundaryViolation(RuntimeError):
    """A single-detector flag was about to be resolved as accept or delete."""
    pass


class Resolution(Enum):
    ACCEPT = "accept"
    QUARANTINE = "quarantine"
    REJECT = "reject"
    ESCALATE = "escalate"


@dataclass
class RecallCandidate:
    record_id: str
    provenance_valid: bool          # must reflect a COMPLETE transitive chain
    provenance_transitive: bool     # False => point-to-point, invariant unsupported
    anomaly_flagged: bool
    anomaly_score: float
    diagnostic: str = ""


def resolve_trust_boundary(cand: RecallCandidate) -> Resolution:
    # Guard: the invariant is undefined without transitive provenance.
    if not cand.provenance_transitive:
        raise ProvenanceIncompleteError(
            f"record {cand.record_id}: provenance is point-to-point; "
            f"agreement invariant cannot be evaluated. Escalate, do not decide."
        )

    pv, af = cand.provenance_valid, cand.anomaly_flagged

    if pv and not af:
        return Resolution.ACCEPT
    if not pv and af:
        return Resolution.REJECT
    if pv and af:
        # Laundering-via-trusted-distiller: quarantine, walk upstream chain.
        return Resolution.QUARANTINE
    # not pv and not af: stale-warrant / forged-but-plausible: quarantine + audit signer.
    return Resolution.QUARANTINE


def promote_to_working_context(cand: RecallCandidate) -> bool:
    decision = resolve_trust_boundary(cand)

    # Enforce: no single-detector flag may reach ACCEPT or REJECT-as-delete directly.
    single_detector = (cand.provenance_valid != cand.anomaly_flagged)
    if single_detector and decision in (Resolution.ACCEPT, Resolution.REJECT):
        raise TrustBoundaryViolation(
            f"record {cand.record_id}: single-detector flag "
            f"(prov={cand.provenance_valid}, anom={cand.anomaly_flagged}) "
            f"resolved to {decision.value}; forbidden."
        )

    if decision is Resolution.ACCEPT:
        return True
    if decision is Resolution.QUARANTINE:
        # Reversible isolation; preserve record + diagnostic for the chain walk.
        return False
    if decision is Resolution.REJECT:
        # Both detectors adverse: safe to drop from the active store.
        return False
    raise TrustBoundaryViolation(
        f"record {cand.record_id}: unexpected resolution {decision}"
    )
