# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-window-mid-task-and-the-summarizer-s-fidelity-guarantees-silently-invert-on-negation-dense-stat.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-window-mid-task-and-the-summarizer-s-fidelity-guarantees-silently-invert-on-negation-dense-stat.warrant.json
# Markdown SHA-256:   8edf4937eed10182f144bf144c1dcdff241847d1f8736cffec80a2f56ca71329
# Code AST SHA-256:   b13b9affe2e246619adcd5c2a27a24307920d161fc3e9ff94ec450074653915f
# Verified Classes:   ConstraintPolarityLossError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ConstraintPolarityLossError(RuntimeError):
    """Raised when a compaction would summarize an untriaged constraint span,
    risking negation/bound inversion that no downstream tool can detect."""
    pass


CONSTRAINT_MARKERS = ("do not", "never", "only if", "only after", "at most",
                      "not before", "under no condition", "except", "unless")


def classify_span(span_text: str) -> str:
    """Return 'constraint' if the span carries prohibitions/bounds, else 'narration'."""
    lowered = span_text.lower()
    if any(marker in lowered for marker in CONSTRAINT_MARKERS):
        return "constraint"
    return "narration"


def compact(spans: list[dict], ledger: list[dict], summarize_fn) -> tuple[str, list[dict]]:
    """
    spans: [{"text": str, "triaged": bool}]
    ledger: append-only structured constraint records (never summarized)
    Refuses to summarize any constraint span that has not been triaged into the ledger.
    """
    summarizable, new_ledger = [], list(ledger)

    for span in spans:
        cls = classify_span(span["text"])
        if cls == "constraint":
            if not span.get("triaged"):
                raise ConstraintPolarityLossError(
                    "Refusing to summarize untriaged constraint span; "
                    "negation/bound inversion would be undetectable downstream. "
                    f"Span head: {span['text'][:120]!r}"
                )
            # Constraint already extracted to ledger; drop prose, keep record.
            continue
        summarizable.append(span["text"])

    summary = summarize_fn("\n".join(summarizable)) if summarizable else ""
    # Re-inject ledger verbatim; it is the only channel that preserves polarity.
    ledger_block = "\n".join(f"[CONSTRAINT] {r}" for r in new_ledger)
    return f"{ledger_block}\n\n{summary}", new_ledger
