# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-lossy-compaction-summary-has-silently-dropped-a-load-bearing-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-lossy-compaction-summary-has-silently-dropped-a-load-bearing-constraint.warrant.json
# Markdown SHA-256:   4c7507c2a1f41d6c1327b9130e44a41a919e3e2d328f9a7024519897e60b5f6f
# Code AST SHA-256:   3dd932c6c03f802136187764bbcd6a74669e03bc2e97337d926212d3787ca3f1
# Verified Classes:   ConstraintLossError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConstraintLossError(RuntimeError):
    """Raised when a compaction summary fails the constraint carry-forward invariant."""
    pass


def audit_compaction(
    pre_directives: list[dict],
    post_directives: list[dict],
    window_turns: int,
    retained_turn_indices: list[int],
) -> None:
    """
    Enforce the constraint carry-forward invariant at a compaction boundary.
    Signals: (1) imperative-mass delta must be zero,
             (2) retained directives must span the window, not cluster at the tail.
    """
    pre_ids = {d["id"] for d in pre_directives}
    post_ids = {d["id"] for d in post_directives}

    dropped = pre_ids - post_ids
    if dropped:
        raise ConstraintLossError(
            f"compaction dropped {len(dropped)} binding constraint(s): {sorted(dropped)}. "
            f"Constraints are not summarizable; pin them to the register and re-compact."
        )

    if retained_turn_indices:
        earliest = min(retained_turn_indices)
        if earliest > 0.8 * window_turns:
            raise ConstraintLossError(
                f"retained directives cluster in the last 20% of the window "
                f"(earliest retained turn {earliest} of {window_turns}); "
                f"recency bias detected, early constraints presumed lost."
            )


def compact_or_refuse(session, summarizer) -> str:
    summary = summarizer.summarize(session.transcript)
    audit_compaction(
        pre_directives=session.directive_register,
        post_directives=extract_directives(summary),
        window_turns=len(session.transcript),
        retained_turn_indices=[d["turn"] for d in extract_directives(summary)],
    )
    return summary
