# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-write-audit-anomaly-score-is-itself-computed-from-poisoned-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-write-audit-anomaly-score-is-itself-computed-from-poisoned-memory.warrant.json
# Markdown SHA-256:   bb7609b72d5ac9206f0f2763849aaef0ef83b9d60f3768167d1282a4e21c6580
# Code AST SHA-256:   0d98c9defc2eb9c007fb87bcc0abc0ad258a7133d8fb50f048e68f05e7ff6339
# Verified Classes:   BaselineCaptureError, ProvenanceGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class BaselineCaptureError(RuntimeError):
    """Raised when an anomaly baseline has absorbed writes it is meant to score."""
    pass


class ProvenanceGate:
    MIN_DISTINCT_LINEAGES = 3

    def __init__(self, frozen_baseline, audit_log):
        # frozen_baseline is write-once; audit_log is append-only and
        # NOT writable by the agent commit path.
        self.baseline = frozen_baseline
        self.audit_log = audit_log

    def score(self, candidate):
        z = self.baseline.zscore(candidate.embedding)
        lineages = self.audit_log.distinct_lineages(candidate.fact_key)
        return z, lineages

    def admit(self, candidate):
        z, lineages = self.score(candidate)

        # Detect baseline capture: a repeated cluster whose anomaly score
        # is FALLING while internal coherence RISES is the fingerprint.
        if self.audit_log.cluster_trend(candidate.fact_key) == "falling_z_rising_coherence":
            raise BaselineCaptureError(
                f"Baseline capture suspected for fact_key={candidate.fact_key!r}: "
                f"z={z:.2f} declining while cluster coherence rising. "
                f"Quarantine and re-derive baseline from audit log."
            )

        # Provenance-diversity gate: recurrence from one lineage is one vote.
        if lineages < self.MIN_DISTINCT_LINEAGES:
            return "quarantine_low_provenance"

        if z > self.baseline.quarantine_threshold:
            return "quarantine_anomalous"

        # Only the auditor may append to the baseline, post-corroboration.
        self.audit_log.record_accepted(candidate)
        return "admit"
