# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-preserving-negative-constraint-invariants-across-long-horizon-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-preserving-negative-constraint-invariants-across-long-horizon-agent-sessions.warrant.json
# Markdown SHA-256:   90e8b8b7b1fe02d75b8b83abb36ea3d2938d491ff5021fd6ddadcffad195190e
# Code AST SHA-256:   253bbd0c90e66250cf7738a1b73463f6897391d0d7dd5ea29a4e6c2fe3d70d71
# Verified Classes:   CompactionRefused, Observability, NegativeConstraint, ConstraintBlock
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class CompactionRefused(RuntimeError):
    """Raised when compaction would drop a silent-violation negative constraint."""
    pass


class Observability(Enum):
    OBSERVABLE = "observable"   # violation triggers a downstream hard error
    SILENT = "silent"           # violation produces no in-session signal


@dataclass(frozen=True)
class NegativeConstraint:
    forbidden_action: str
    scope: str
    source_turn: int
    observability: Observability
    revoked_at_turn: int | None = None

    def is_active(self, at_turn: int) -> bool:
        return self.revoked_at_turn is None or at_turn < self.revoked_at_turn


@dataclass
class ConstraintBlock:
    """Append-only, never-compacted, re-injected at every resume."""
    constraints: list[NegativeConstraint] = field(default_factory=list)

    def active(self, at_turn: int) -> Iterable[NegativeConstraint]:
        return (c for c in self.constraints if c.is_active(at_turn))

    def render(self, at_turn: int) -> str:
        lines = ["## BINDING CONSTRAINTS (do not summarize, do not omit)"]
        for c in self.active(at_turn):
            lines.append(
                f"- FORBIDDEN: {c.forbidden_action} on {c.scope} "
                f"(source turn {c.source_turn}, {c.observability.value})"
            )
        return "\n".join(lines)


def compact(
    raw_context: str,
    constraints: ConstraintBlock,
    current_turn: int,
    summarizer_instruction: str,
) -> tuple[str, ConstraintBlock]:
    """
    Decide whether compaction is safe. Returns (resumed_context, block).
    Refuses when a silent-violation constraint is active and the
    summarizer instruction does not name the prohibition category.
    """
    silent_active = [
        c for c in constraints.active(current_turn)
        if c.observability is Observability.SILENT
    ]
    instruction_names_prohibitions = any(
        tok in summarizer_instruction.lower()
        for tok in ("prohibit", "forbidden", "never", "restriction")
    )

    if silent_active and not instruction_names_prohibitions:
        # Escalation path: do not summarize; truncate oldest routine turns
        # and preserve constraint-bearing turns by index.
        raise CompactionRefused(
            "Refusing lossy compaction: "
            f"{len(silent_active)} silent-violation constraint(s) active "
            f"(e.g. {silent_active[0].forbidden_action!r} from turn "
            f"{silent_active[0].source_turn}) and summarizer instruction "
            "does not name the prohibition category. "
            "Use truncation-by-turn-index or add a constraint block."
        )

    # Safe path: summarize narrative, then re-attach the constraint block.
    summary = _summarize(raw_context, summarizer_instruction)
    block = constraints.render(current_turn)
    resumed = f"{block}\n\n{summary}"
    return resumed, constraints


def _summarize(context: str, instruction: str) -> str:
    # Placeholder for the actual probabilistic summarizer call.
    return f"[summary under: {instruction!r}]"
