# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-tool-call-and-the-summarizer-re-emits-a-stale-tool-result-as-fresh-ground-truth.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-tool-call-and-the-summarizer-re-emits-a-stale-tool-result-as-fresh-ground-truth.warrant.json
# Markdown SHA-256:   b9e0192879a011f0dcc245b7cddee86b96229e0c371c6ff1579859f39c0bdac1
# Code AST SHA-256:   8933e1b3297c283a1f1f405bc6484f5a3d459761c8918ec762e1dfaf4a73c4e0
# Verified Classes:   StaleCompactedAssertionError, CompactedAssertion, ResourceEpoch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleCompactedAssertionError(RuntimeError):
    """Raised when a write-path consumes a compacted tool assertion whose
    mutation epoch predates the resource's current epoch."""
    pass


@dataclass
class CompactedAssertion:
    source_tool: str
    resource_id: str
    mutation_seq_at_read: int
    value: str
    compacted_at_step: int
    superseded_by: Optional["CompactedAssertion"] = None


@dataclass
class ResourceEpoch:
    """Tracks the last mutation sequence per resource. Incremented by any
    mutating tool (write, edit, patch) before its result is emitted."""
    seq: dict = field(default_factory=dict)

    def bump(self, resource_id: str) -> int:
        self.seq[resource_id] = self.seq.get(resource_id, 0) + 1
        return self.seq[resource_id]

    def current(self, resource_id: str) -> int:
        return self.seq.get(resource_id, 0)


def consume_for_write(assertion: CompactedAssertion, epochs: ResourceEpoch) -> str:
    """Write-path policy: a compacted evidential value may only be consumed
    if it was read at the resource's current mutation epoch. Otherwise the
    caller must re-read the resource verbatim before proceeding."""
    current = epochs.current(assertion.resource_id)
    if assertion.mutation_seq_at_read < current:
        raise StaleCompactedAssertionError(
            f"compacted assertion for {assertion.resource_id!r} read at epoch "
            f"{assertion.mutation_seq_at_read} but resource is at epoch {current}; "
            f"value {assertion.value!r} is stale — re-read before writing"
        )
    if assertion.superseded_by is not None:
        raise StaleCompactedAssertionError(
            f"assertion for {assertion.resource_id!r} was superseded at step "
            f"{assertion.superseded_by.compacted_at_step}; consume the successor"
        )
    return assertion.value


def dedup_gate(a: CompactedAssertion, b: CompactedAssertion,
               cosine_sim: float, threshold: float = 0.92) -> Optional[CompactedAssertion]:
    """Semantic-redundancy dedup, gated on mutation epoch. Returns the
    assertion to retain, or None if both must be kept verbatim."""
    if a.resource_id != b.resource_id:
        return None  # never dedup across resources
    if cosine_sim < threshold:
        return None
    if a.mutation_seq_at_read != b.mutation_seq_at_read:
        # Same resource, different mutation epochs: NOT duplicates.
        # Keep the newer, mark the older superseded, never collapse to one value.
        newer, older = (a, b) if a.mutation_seq_at_read > b.mutation_seq_at_read else (b, a)
        older.superseded_by = newer
        return newer
    # Same epoch: safe to collapse; keep first-seen, both values identical.
    return a
