# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-auto-compact-a-long-horizon-agent-session-because-the-summarizer-cannot-guarantee-a-lossy-but-safe-transf.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-auto-compact-a-long-horizon-agent-session-because-the-summarizer-cannot-guarantee-a-lossy-but-safe-transf.warrant.json
# Markdown SHA-256:   f37feecdd28504345a466756e56cef398854854f3a257c36481d4b3bfbb00851
# Code AST SHA-256:   2e4fdc2c046f0faa13b70d003ce58e2c0438950f25670a2dcccd19bde43819c5
# Verified Classes:   OpenSpanCompactionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class OpenSpanCompactionError(RuntimeError):
    """Raised when auto-compaction is attempted on a span that is not causally closed.

    A span is closed only if it has no pending tool calls, all user constraints are
    captured verbatim in the summary, all failure signatures are indexed, and all
    decisions have externalized rationale. Compacting an open span silently drops
    facts that later turns must re-derive.
    """


def assert_span_closed(span, summary, constraint_schema, failure_index):
    if span.pending_tool_calls:
        raise OpenSpanCompactionError(
            f"span {span.id} has {len(span.pending_tool_calls)} non-terminal tool calls; "
            "compaction would drop the only witness of their state"
        )

    missing = [
        c for c in constraint_schema.extract(span)
        if c.stable_id not in summary.constraint_ids
    ]
    if missing:
        raise OpenSpanCompactionError(
            f"span {span.id} drops {len(missing)} user constraints "
            f"(e.g. {missing[0].stable_id!r}); summarizer cannot certify their loss is safe"
        )

    unindexed = [
        f for f in span.failed_attempts
        if f.signature not in failure_index and f.signature not in summary.failure_signatures
    ]
    if unindexed:
        raise OpenSpanCompactionError(
            f"span {span.id} drops {len(unindexed)} failure signatures "
            f"(e.g. {unindexed[0].signature!r}); agent would re-derive a known failure"
        )

    for decision in span.decisions:
        if not decision.externalized_artifact:
            raise OpenSpanCompactionError(
                f"span {span.id} decision {decision.id} has no externalized rationale; "
                "summary paraphrase is not a durable witness"
            )

    return True


def maybe_compact(session, watermark=0.70):
    if session.budget_used() < watermark:
        return None
    span = session.oldest_open_span()
    summary = session.summarizer.summarize(span)
    assert_span_closed(span, summary, session.constraint_schema, session.failure_index)
    return session.substitute(span, summary)
