# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-compaction-triggered-tool-call-replay-from-duplicating-side-effects-in-long-horizon-agent-runs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-compaction-triggered-tool-call-replay-from-duplicating-side-effects-in-long-horizon-agent-runs.warrant.json
# Markdown SHA-256:   a340fa4c9c5e893dd44ea39a275efa1894c7774b19fc1368963fd096b973a729
# Code AST SHA-256:   a6a983496b028c35a351d556f724257ffb0c03074ed3c3f57874ac3a1d8a2019
# Verified Classes:   CompactionReplayError, CommitEntry, CommitLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionReplayError(RuntimeError):
    """Raised when a compaction cut would orphan or re-open a committed action."""
    pass


@dataclass
class CommitEntry:
    tool: str
    args: dict
    seq: int
    idempotency_key: str
    result_id: Optional[str] = None


@dataclass
class CommitLog:
    entries: list = field(default_factory=list)
    watermark: int = 0  # highest seq durably committed

    def record(self, tool: str, args: dict, seq: int) -> CommitEntry:
        key = hashlib.sha256(
            f"{tool}:{sorted(args.items())}:{seq}".encode()
        ).hexdigest()[:16]
        entry = CommitEntry(tool=tool, args=args, seq=seq, idempotency_key=key)
        self.entries.append(entry)
        self.watermark = max(self.watermark, seq)
        return entry


def assert_safe_to_compact(
    in_flight_calls: int,
    unresolved_intents: int,
    log: CommitLog,
    re_inject_through: int,
) -> None:
    """Gate a compaction trigger. Raises if the cut would leak causal state."""
    if in_flight_calls != 0:
        raise CompactionReplayError(
            f"compaction fired with {in_flight_calls} in-flight tool call(s); "
            "outcome was never observed by the summarizer"
        )
    if unresolved_intents != 0:
        raise CompactionReplayError(
            f"{unresolved_intents} unresolved intended action(s); digest would "
            "re-present them as pending and invite re-execution"
        )
    if re_inject_through < log.watermark:
        # The digest would summarize past a committed action without carrying
        # its identity forward -> replay candidate.
        missing = [
            e.idempotency_key
            for e in log.entries
            if e.seq > re_inject_through and e.seq <= log.watermark
        ]
        raise CompactionReplayError(
            f"commit-log watermark {log.watermark} exceeds re-injection point "
            f"{re_inject_through}; {len(missing)} committed action(s) would be "
            f"projected lossily (keys: {missing[:3]}...)"
        )
