# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-compaction-boundary-has-been-crossed-mid-task-rather-than-at-a-phase-transition.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-compaction-boundary-has-been-crossed-mid-task-rather-than-at-a-phase-transition.warrant.json
# Markdown SHA-256:   13a6893fa165aa93a0b80826be9bee77a39b068debd311d29596ee2318a6ec94
# Code AST SHA-256:   ce2976d7b90397511951a26773d062236b8ec7a80adc5ce4972c64a508c8bf6b
# Verified Classes:   OpenTailCompactionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OpenTailCompactionError(RuntimeError):
    """Raised when a budget-triggered compaction would fire on an open trace tail."""


def compact_if_safe(trace, token_count, soft_limit, hard_limit, summary_fn):
    tail = trace[-1]
    tail_is_open = (
        tail.role == "tool_result" and not tail.consumed
    ) or (
        tail.role == "reasoning" and not tail.committed
    ) or bool(tail.unresolved_references)

    if not tail_is_open:
        return summary_fn(trace), "phase"

    headroom = hard_limit - token_count
    if headroom > 0:
        # defer: let the tail close naturally
        return None, "deferred"

    # no headroom: checkpoint-compact, preserve open tail verbatim
    preserved = trace[-1:]
    summarized = summary_fn(trace[:-1])
    if not summarized:
        raise OpenTailCompactionError(
            f"cannot summarize trace[:-1]; open tail {tail.role!r} "
            f"with refs {tail.unresolved_references!r} would be orphaned"
        )
    return (summarized, preserved), "checkpoint"


def assert_no_orphaned_references(summary_text, tail):
    for ref in tail.unresolved_references:
        if ref not in summary_text:
            raise OpenTailCompactionError(
                f"reference {ref!r} in tail is absent from summary; "
                f"compaction would orphan it"
            )
