# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-hierarchically-and-evicts-the-only-leaf-that-carried-a-negative-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-hierarchically-and-evicts-the-only-leaf-that-carried-a-negative-constraint.warrant.json
# Markdown SHA-256:   ed0bf766b57425968e51184b90e900c154a8a3faea0d955d2e53ee47f52244b1
# Code AST SHA-256:   96032ca25239028b5baf9745c5da0377890174828f9d690b44aec9abf6fc5ef4
# Verified Classes:   ConstraintPolarityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConstraintPolarityError(RuntimeError):
    """Raised when hierarchical compaction would evict a negative constraint
    without preserving it verbatim in the pinned constraint ledger."""
    pass


PROHIBITION_MARKERS = (
    "do not", "don't", "never", "must not", "mustn't",
    "avoid", "reject", "forbidden", "on purpose", "intentionally",
)


def is_prohibition(span_text: str) -> bool:
    low = span_text.lower()
    return any(marker in low for marker in PROHIBITION_MARKERS)


def binds_to_action_entity(span_text: str, action_spans: list[str]) -> bool:
    # crude entity overlap: any capitalized token or backticked identifier
    # shared between the prohibition span and a positive-action span
    def entities(text: str) -> set[str]:
        toks = set()
        for raw in text.replace("`", " ").split():
            cleaned = raw.strip(".,;:()[]\"'")
            if cleaned and (cleaned[0].isupper() or "-" in cleaned or "_" in cleaned):
                toks.add(cleaned.lower())
        return toks

    return bool(entities(span_text) & set().union(*(entities(s) for s in action_spans)))


def compact(spans: list[str], ledger: list[str], budget_tokens: int,
            token_count) -> tuple[list[str], list[str]]:
    candidates, promoted = [], []
    for span in spans:
        if is_prohibition(span) and binds_to_action_entity(span, spans):
            promoted.append(span)          # verbatim, never summarized
        else:
            candidates.append(span)

    new_ledger = ledger + [p for p in promoted if p not in ledger]

    if token_count(new_ledger) > budget_tokens:
        # The ledger is the fixed point. Never compress it. Fail the compaction.
        raise ConstraintPolarityError(
            f"constraint ledger requires {token_count(new_ledger)} tokens, "
            f"budget is {budget_tokens}; evicting summaries is permitted, "
            f"evicting constraints is not"
        )

    summarized = [f"<summary of {len(candidates)} spans>" if candidates else ""]
    return summarized, new_ledger


def execute_action(action: str, ledger: list[str]) -> None:
    for entry in ledger:
        if binds_to_action_entity(entry, [action]) and is_prohibition(entry):
            raise ConstraintPolarityError(
                f"action {action!r} intersects pinned constraint {entry!r}; "
                f"halt and re-confirm before proceeding"
            )
    # ... perform action ...
