# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-write-forget-log-as-poisoned-rather-than-merely-lossy-auditing-tombstone-resurrection-and-silent-forget.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-write-forget-log-as-poisoned-rather-than-merely-lossy-auditing-tombstone-resurrection-and-silent-forget.warrant.json
# Markdown SHA-256:   a1e2645b10a7efb09e0daca499b8ac398f645135f8ad8bec38848657b4e4887d
# Code AST SHA-256:   6e9a8f186291c19c50a7f3477054bc9c78798c775d03b42ea0f5cf232613e325
# Verified Classes:   TombstoneResurrectionError, WriteRecord, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class TombstoneResurrectionError(RuntimeError):
    """Raised when a tombstoned key is live with a post-forget mutation
    that carries no external provenance — a poisoning signature, not lag."""
    pass


@dataclass
class WriteRecord:
    key: str
    payload: bytes
    timestamp: float
    provenance: Optional[str]   # tool call ID, user turn ID, or peer warrant
    author_instance: str


@dataclass
class Tombstone:
    key: str
    forgotten_at: float
    payload_hash_at_forget: str


def audit_key(
    key: str,
    tombstone: Tombstone,
    live_payload: Optional[bytes],
    post_forget_writes: list[WriteRecord],
    now: float,
    grace_window: float,
) -> str:
    if live_payload is None:
        return "consistent"

    if now - tombstone.forgotten_at < grace_window:
        return "lag_suppressed"

    current_hash = hashlib.sha256(live_payload).hexdigest()
    if current_hash == tombstone.payload_hash_at_forget:
        return "stuck_forget"

    external = [
        w for w in post_forget_writes
        if w.timestamp > tombstone.forgotten_at
        and w.provenance is not None
        and w.author_instance != "self"
    ]
    if external:
        return "legitimate_reauthorization"

    self_authored = [
        w for w in post_forget_writes
        if w.timestamp > tombstone.forgotten_at
    ]
    if self_authored:
        raise TombstoneResurrectionError(
            f"key={key} resurrected at t={self_authored[0].timestamp} "
            f"by instance={self_authored[0].author_instance} "
            f"with provenance={self_authored[0].provenance!r}; "
            f"payload hash diverged from forget-time snapshot. "
            f"Quarantine key, freeze writer, replay forget log."
        )
    raise TombstoneResurrectionError(
        f"key={key} live with mutated payload but no post-forget write record; "
        f"index corruption suspected."
    )
