# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-provenance-weights-the-self-referential-poisoning-edge-in-forget-audit-admission.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-provenance-weights-the-self-referential-poisoning-edge-in-forget-audit-admission.warrant.json
# Markdown SHA-256:   fc1df3b19d11adc8226fadffbf0bf36b2ebcf9c7376a3ce3d7ccfda1863b8a00
# Code AST SHA-256:   04db4c77c772fdae48be4428c7b3e62cdc32811ec9ae502a695feeb310e8c4ce
# Verified Classes:   ProvenanceFeedbackError, AdmissionController
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceFeedbackError(RuntimeError):
    """Raised when admission scoring reads audit-trail state mutated by the scored source."""
    pass


class AdmissionController:
    def __init__(self, freeze_window_cycles: int = 3):
        self.freeze_window = freeze_window_cycles
        # source_id -> cycle index of last audit-trail mutation attributable to source
        self.last_mutation_cycle: dict[str, int] = {}
        # source_id -> (cycle, frozen precision, frozen corroboration) snapshot
        self.frozen_snapshot: dict[str, tuple[int, float, int]] = {}

    def record_audit_mutation(self, source_id: str, cycle: int) -> None:
        self.last_mutation_cycle[source_id] = cycle

    def freeze_baseline(self, source_id: str, cycle: int, precision: float, corroboration: int) -> None:
        self.frozen_snapshot[source_id] = (cycle, precision, corroboration)

    def score(self, source_id: str, tier: float, recency: float, cycle: int) -> float:
        if source_id not in self.frozen_snapshot:
            raise ProvenanceFeedbackError(
                f"no frozen baseline for source {source_id!r}; refusing to score against live audit state"
            )
        frozen_cycle, precision, corroboration = self.frozen_snapshot[source_id]
        last_mut = self.last_mutation_cycle.get(source_id, -10**9)
        # Invariant: if the source mutated the audit trail within the freeze window,
        # the frozen baseline is stale and the score would be self-referential.
        if last_mut > frozen_cycle and (cycle - last_mut) <= self.freeze_window:
            raise ProvenanceFeedbackError(
                f"source {source_id!r} mutated audit trail at cycle {last_mut}, "
                f"freeze baseline at cycle {frozen_cycle}, current cycle {cycle}; "
                f"score would read its own writes"
            )
        return 0.4 * tier + 0.3 * precision + 0.2 * min(corroboration, 5) / 5.0 + 0.1 * recency

    def admit(self, source_id: str, tier: float, recency: float, cycle: int, threshold: float = 0.72) -> bool:
        s = self.score(source_id, tier, recency, cycle)
        return s >= threshold
