# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-automatic-context-compaction-has-silently-dropped-a-negative-constraint-it-must-not-violate.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-automatic-context-compaction-has-silently-dropped-a-negative-constraint-it-must-not-violate.warrant.json
# Markdown SHA-256:   51633c3cb37d16843dc1e4654325b913d81eb9dece770e889a93b710d288b591
# Code AST SHA-256:   2ce4d611d9c3204590ee7f2d7d37b9d0438fadd025a0e3e0d5348b12a64a66e0
# Verified Classes:   ConstraintMonotonicityViolation, Constraint, DurableConstraintRegister
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ConstraintMonotonicityViolation(RuntimeError):
    """Raised when a compaction pass shrinks the active negative-constraint set.

    A shrunk constraint set is indistinguishable from a satisfied one, so this
    must be a hard error, never a warning the agent is expected to reason about.
    """
    pass


@dataclass(frozen=True)
class Constraint:
    cid: str
    text: str          # e.g. "do not modify billing-ledger IAM role"
    source_turn: int
    principal: str     # who issued it; only they may clear it


@dataclass
class DurableConstraintRegister:
    """Lives OUTSIDE the compactable context region. Append-only except for
    explicit, principal-authorized clears. Never summarized."""
    _active: dict = field(default_factory=dict)

    def issue(self, c: Constraint) -> None:
        self._active[c.cid] = c

    def clear(self, cid: str, by_principal: str) -> None:
        c = self._active.get(cid)
        if c is None:
            return
        if by_principal != c.principal:
            raise ConstraintMonotonicityViolation(
                f"principal {by_principal!r} may not clear constraint {cid!r} "
                f"issued by {c.principal!r}"
            )
        del self._active[cid]

    def snapshot(self) -> FrozenSet[str]:
        return frozenset(self._active)


def guarded_compaction(
    register: DurableConstraintRegister,
    compact_fn,
    transcript: list,
) -> tuple:
    """Run a compaction pass, then assert the constraint set did not shrink.

    compact_fn is the lossy summarizer. It is NOT trusted to preserve
    constraints; the register is the source of truth and is re-injected
    verbatim after compaction.
    """
    before = register.snapshot()

    compacted = compact_fn(transcript)  # lossy; may drop prohibitions

    after = register.snapshot()  # register untouched by compact_fn by design
    if not (before <= after):
        # Defensive: catches a compact_fn that (wrongly) mutates the register.
        lost = before - after
        raise ConstraintMonotonicityViolation(
            f"compaction dropped constraints {sorted(lost)}; "
            f"refusing to continue with a widened action space"
        )

    # Re-inject the durable constraints verbatim ahead of the summary so the
    # model sees them with full polarity, independent of the summarizer.
    reinjected = [register._active[cid] for cid in sorted(after)]
    return compacted, reinjected


def pre_tool_call_gate(
    register: DurableConstraintRegister,
    proposed_tool: str,
    proposed_args: dict,
) -> None:
    """Structural gate: block any action whose target intersects an active
    prohibition. This is the enforcement the model cannot be trusted to do
    after compaction, because the prohibition may no longer be in its context."""
    for c in register._active.values():
        target = c.text.split()[-1] if c.text else ""
        if target and target in str(proposed_args.get("target", "")):
            raise ConstraintMonotonicityViolation(
                f"tool {proposed_tool!r} on {proposed_args.get('target')!r} "
                f"violates active constraint {c.cid!r} ({c.text!r}) "
                f"issued at turn {c.source_turn} by {c.principal!r}"
            )
