# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-lossy-irreversible-transform-and-refuse-to-resume-a-long-horizon-task-from-a-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-lossy-irreversible-transform-and-refuse-to-resume-a-long-horizon-task-from-a-summary.warrant.json
# Markdown SHA-256:   52d7fb45217c35f95ce65f7c687148fe38686e0a073b4745d73aaecd41ac2005
# Code AST SHA-256:   85bbd4614f4f4c7b2604a398801d3e9ec9e7ad5e222599a51cc839cc2215d5ed
# Verified Classes:   LossyCompactionResumeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class LossyCompactionResumeError(RuntimeError):
    """Raised when an agent attempts to resume a long-horizon task from an
    irreversible summary that lacks a verified constraint/failure sidecar."""


def compact_and_resume(span_tokens, summary, sidecar, span_had_constraints, span_had_failures):
    # Phase 1: extraction must have produced a sidecar for any span that
    # carried binding constraints or tool-failure evidence.
    constraints = sidecar.get("constraints", [])
    failures = sidecar.get("failures", [])

    if span_had_constraints and not constraints:
        raise LossyCompactionResumeError(
            "compaction rejected: span contained binding constraints but "
            "extraction produced an empty constraint set; refusing to drop "
            "tokens into an unrecoverable summary"
        )
    if span_had_failures and not failures:
        raise LossyCompactionResumeError(
            "compaction rejected: span contained tool failures but no failure "
            "ledger was extracted; resumed agent would re-walk known-bad paths"
        )

    # Phase 2: only now is it legal to drop the source tokens.
    state = {
        "summary": summary,
        "lossy": True,
        "sidecar": {"constraints": constraints, "failures": failures},
        "source_tokens_evicted": True,
    }

    # Phase 3: resume must load the sidecar or fail closed.
    if state["lossy"] and not state["sidecar"]["constraints"] and span_had_constraints:
        raise LossyCompactionResumeError(
            "resume aborted: lossy state has no constraint sidecar to re-read"
        )
    return state
