# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-relevance-score-hysteresis-when-a-self-editing-context-policy-rewrites-its-own-eviction-threshold-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-relevance-score-hysteresis-when-a-self-editing-context-policy-rewrites-its-own-eviction-threshold-mid-task.warrant.json
# Markdown SHA-256:   c5bd7b15ab2cda1eb49dba065319f56ef9e0c02e3eb465a71a3218402d8812dc
# Code AST SHA-256:   e31ee5ef6b46ce3c8e3d67eb0076ef738873831ab9a57db1dff6d9bccc6ba65f
# Verified Classes:   PolicyEvictionViolation, Span, ContextPolicy, ContextManager
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class PolicyEvictionViolation(RuntimeError):
    """Raised when a self-editing context policy would evict or rewrite a span
    in a way that breaks score anchoring, policy immutability, or tombstone
    detectability."""
    pass


@dataclass
class Span:
    span_id: str
    content: str
    anchored_score: float          # score at first write; never recomputed
    rewritten: bool = False
    tombstoned: bool = False

    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class ContextPolicy:
    tau: float
    epoch: int = 0
    max_rewrite_delta: float = 0.0  # measured per operator; 0 means unmeasured

    def amend(self, new_tau: float, reason: str) -> None:
        # Policy may only be amended through an explicit, logged call that is
        # NOT triggered by buffer-pressure observation in the same step.
        if reason.strip() == "":
            raise PolicyEvictionViolation("policy amendment requires a logged reason")
        self.tau = new_tau
        self.epoch += 1


class ContextManager:
    def __init__(self, policy: ContextPolicy):
        self.policy = policy
        self.spans: dict[str, Span] = {}
        self.tombstones: dict[str, dict] = {}  # hash -> metadata, outside buffer

    def write(self, span_id: str, content: str, score: float) -> Span:
        span = Span(span_id=span_id, content=content, anchored_score=score)
        self.spans[span_id] = span
        return span

    def rewrite(self, span_id: str, new_content: str, new_score: float) -> None:
        span = self.spans[span_id]
        if span.tombstoned:
            raise PolicyEvictionViolation(f"cannot rewrite tombstoned span {span_id}")
        delta = abs(new_score - span.anchored_score)
        if self.policy.max_rewrite_delta == 0.0:
            raise PolicyEvictionViolation(
                f"operator score-delta unmeasured; refusing rewrite of {span_id}"
            )
        if delta > self.policy.max_rewrite_delta:
            raise PolicyEvictionViolation(
                f"rewrite of {span_id} moved score by {delta:.3f} > bound "
                f"{self.policy.max_rewrite_delta:.3f}; evict-and-tombstone instead"
            )
        span.content = new_content
        span.rewritten = True
        # anchored_score deliberately NOT updated

    def evict(self, span_id: str, reason: str) -> None:
        span = self.spans[span_id]
        if span.anchored_score >= self.policy.tau and not span.tombstoned:
            # eviction only permitted below tau, evaluated on anchored score
            raise PolicyEvictionViolation(
                f"span {span_id} anchored_score {span.anchored_score:.3f} >= tau "
                f"{self.policy.tau:.3f}; eviction would drop live evidence"
            )
        span.tombstoned = True
        self.tombstones[span.content_hash()] = {
            "span_id": span_id,
            "anchored_score": span.anchored_score,
            "reason": reason,
            "epoch": self.policy.epoch,
        }
        del self.spans[span_id]

    def ingest_tool_output(self, content: str) -> str:
        h = hashlib.sha256(content.encode()).hexdigest()
        if h in self.tombstones:
            meta = self.tombstones[h]
            return f"REDERIVED:{meta['span_id']}:downgrade_to_candidate"
        return "FRESH"
