# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-write-audit-anomaly-scores-from-true-memory-poisoning-when-the-scoring-window-is-shorter-than-the-poisoning-dwell-t.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-write-audit-anomaly-scores-from-true-memory-poisoning-when-the-scoring-window-is-shorter-than-the-poisoning-dwell-t.warrant.json
# Markdown SHA-256:   aaf954ce922f351ecf9dfb49bd445fd25560e249d971a0d249a58a0d4bdec08d
# Code AST SHA-256:   152f7b0489d931681b8d9bab3c4b584ecfa7f9aa1ab34d2c92f84cd76507c16a
# Verified Classes:   WindowDwellViolation, PoisoningAttributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class WindowDwellViolation(RuntimeError):
    """Raised when a write-audit anomaly score is attributed to a write
    whose dwell interval is not fully contained in the scoring window."""
    pass


class PoisoningAttributionError(RuntimeError):
    """Raised when remediation targets a read entry rather than the
    poison write because the scoring window severed the causal link."""
    pass


def attribute_breach(
    breach_window_writes: list[dict],
    breach_window_score: float,
    threshold: float,
    window_seconds: int,
    p95_dwell_seconds: int,
    read_entries_in_window: list[str],
) -> dict:
    if window_seconds < p95_dwell_seconds:
        raise WindowDwellViolation(
            f"scoring window {window_seconds}s < p95 dwell {p95_dwell_seconds}s; "
            "write-attribution is invalid, escalate to retroactive re-score"
        )

    breaching_writes = [
        w for w in breach_window_writes if w.get("individual_contribution", 0.0) >= threshold
    ]

    if not breaching_writes:
        raise PoisoningAttributionError(
            f"breach score {breach_window_score:.3f} has no individually-breaching write; "
            f"refusing to remediate read entries {read_entries_in_window!r} — "
            "classify as diffuse poisoning or widen window to >= 2x dwell"
        )

    return {
        "target_write_id": breaching_writes[0]["write_id"],
        "attribution": "write",
        "score": breach_window_score,
        "window_seconds": window_seconds,
        "dwell_seconds": p95_dwell_seconds,
    }


def remediate(breach: dict) -> str:
    if breach.get("attribution") != "write":
        raise PoisoningAttributionError(
            "remediation invoked on non-write attribution; poison remains live"
        )
    return f"quarantined write {breach['target_write_id']}"
