# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-segment-because-compaction-would-destroy-a-load-bearing-negative-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-segment-because-compaction-would-destroy-a-load-bearing-negative-constraint.warrant.json
# Markdown SHA-256:   7b28e1df41076e08684d27ef9bed257c664a2e1bad500b0e1e1916ef287849d5
# Code AST SHA-256:   f25627b1b01f20980474fdfb7450bd9791cbf1161a60d7d9a540c7dc2aac8c6e
# Verified Classes:   CompactionInvariantViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction pass would destroy a load-bearing negative constraint."""
    pass


def compact_segment(constraints, summary_fn, reachable):
    """
    constraints: list of dicts with keys: referent, modality ("prohibition"|"advisory"), reason
    summary_fn: callable that compresses positive context only
    reachable: set of referents still reachable by the current plan graph
    """
    pinned = []
    compressible = []

    for c in constraints:
        if c["modality"] == "prohibition" and c["referent"] in reachable:
            # Must be carried verbatim; never paraphrased into an advisory.
            pinned.append(c)
        elif c["modality"] == "prohibition" and c["referent"] not in reachable:
            # Downgrade permitted only with proof of unreachability.
            compressible.append({**c, "modality": "advisory", "proof": "referent-unreachable"})
        else:
            compressible.append(c)

    # Guard: the summary must not reintroduce the forbidden referent as a domain token.
    summary = summary_fn(compressible)
    for c in pinned:
        if c["referent"] in summary:
            raise CompactionInvariantViolation(
                f"Compacted summary mentions pinned referent {c['referent']!r} "
                f"without its prohibition operator; planner could re-derive the "
                f"forbidden action. Refusing compaction."
            )

    # Guard: no prohibition may be silently absent from both pin set and summary.
    for c in constraints:
        if c["modality"] == "prohibition" and c["referent"] in reachable:
            if c not in pinned:
                raise CompactionInvariantViolation(
                    f"Load-bearing prohibition on {c['referent']!r} was evicted."
                )

    return {"pinned": pinned, "summary": summary}
