# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-detects-a-skill-injection-via-manifest-diffing-but-the-behavioral-baseline-has-already-silently-absorbed-the-injected-to.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-detects-a-skill-injection-via-manifest-diffing-but-the-behavioral-baseline-has-already-silently-absorbed-the-injected-to.warrant.json
# Markdown SHA-256:   c133443376df958eeda0f42fadbc5a0683c679948e904601e654c35f58fd9ec5
# Code AST SHA-256:   3d67888fa0f5e50d7c2cf15d8ac3cc4b3ae29848cfb407969c4c7dfbff86f5d7
# Verified Classes:   BaselineContaminationError, SkillRecord, Baseline
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class BaselineContaminationError(RuntimeError):
    """Raised when an anomaly verdict would be issued for a skill whose
    first observation falls inside the baseline's reference window, i.e.
    the baseline has learned the skill's behavior from the skill itself."""
    pass


@dataclass
class SkillRecord:
    name: str
    first_attested_epoch: int
    first_observed_epoch: int
    quarantined: bool = True
    sample_count: int = 0


@dataclass
class Baseline:
    window_start_epoch: int
    min_quarantine_samples: int = 50


def anomaly_verdict(
    skill: SkillRecord,
    baseline: Baseline,
    observed_zscore: float,
    audit_cycles_survived: int,
) -> str:
    # Invariant: a skill may only receive a NORMAL/ANOMALOUS verdict once it has
    # (a) accumulated enough samples AND (b) survived a full manifest audit cycle,
    # AND (c) it was first observed at or before the baseline window start.
    if skill.first_observed_epoch > baseline.window_start_epoch:
        raise BaselineContaminationError(
            f"skill {skill.name!r} first observed at epoch "
            f"{skill.first_observed_epoch} but baseline window starts at "
            f"{baseline.window_start_epoch}; verdict would be self-referential"
        )

    if skill.quarantined or skill.sample_count < baseline.min_quarantine_samples:
        return "UNCERTIFIED"

    if audit_cycles_survived < 1:
        # Attestation has not outlived a full audit cycle; still cold-start.
        return "UNCERTIFIED"

    return "ANOMALOUS" if abs(observed_zscore) > 3.0 else "NORMAL"


def audit_gate(skills: list[SkillRecord], baseline: Baseline) -> dict[str, str]:
    verdicts: dict[str, str] = {}
    for s in skills:
        try:
            verdicts[s.name] = anomaly_verdict(
                s, baseline, observed_zscore=0.0, audit_cycles_survived=0
            )
        except BaselineContaminationError as exc:
            # Fail closed: an auditor must never see a fabricated clean verdict.
            raise BaselineContaminationError(
                f"audit aborted: {exc}"
            ) from exc
    return verdicts
