# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-horizon-when-auto-compaction-silently-promotes-a-stale-tool-result-into-durable-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-horizon-when-auto-compaction-silently-promotes-a-stale-tool-result-into-durable-memory.warrant.json
# Markdown SHA-256:   bc1cb958b6c223b456b7051d931574c10999467d44f6dba89d4fff21fc429fd0
# Code AST SHA-256:   33a6e3facd4863e32a9d6871087efa6843b87bab45edc2b576c9bbf31b30c81f
# Verified Classes:   CompactionInvariantViolation, Claim, MutationLog
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class CompactionInvariantViolation(RuntimeError):
    """Raised when a claim is promoted across the compaction horizon without liveness."""
    pass

@dataclass
class Claim:
    key: str                 # e.g. "config.yaml:timeout"
    value: str               # e.g. "30"
    observed_at_turn: int
    generation: int = 0      # 0 = raw observation; >0 = arrived via summary
    invalidated_by: Optional[str] = None  # resource key of a later mutation

@dataclass
class MutationLog:
    # resource_key -> turn index of last write
    last_write: dict[str, int] = field(default_factory=dict)

    def touched_after(self, resource: str, turn: int) -> bool:
        return self.last_write.get(resource, -1) > turn

def compact(claims: list[Claim], horizon: int, log: MutationLog) -> list[Claim]:
    """Fold claims up to `horizon` into durable memory, enforcing liveness."""
    promoted: list[Claim] = []
    for c in claims:
        if c.observed_at_turn > horizon:
            promoted.append(c)  # not folded; stays live
            continue
        resource = c.key.split(":")[0]
        if log.touched_after(resource, c.observed_at_turn):
            # Observation is stale relative to a later write. Do NOT promote as fact.
            raise CompactionInvariantViolation(
                f"claim {c.key}={c.value} observed at turn {c.observed_at_turn} "
                f"was invalidated by a write to {resource} after the horizon; "
                f"re-observe or mark STALE_UNVERIFIED before folding."
            )
        # A summary-of-summary must not raise confidence; bump generation only.
        promoted.append(Claim(
            key=c.key, value=c.value,
            observed_at_turn=c.observed_at_turn,
            generation=c.generation + 1,
        ))
    return promoted
