# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-as-a-lossy-non-commutative-projection-rather-than-a-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-as-a-lossy-non-commutative-projection-rather-than-a-checkpoint.warrant.json
# Markdown SHA-256:   50dc86949921b5695ce27f15ad8986412f232ebbc339edaed335935f4e73664e
# Code AST SHA-256:   4797586ce34d1ac597923c0d24ab2cf9d110400b106cad6aab0d0b5e3c61b5db
# Verified Classes:   CompactionSeamError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionSeamError(RuntimeError):
    """Raised when an auto-compaction seam would fall inside an open reasoning arc
    or would retain a belief while evicting its falsification set."""
    pass


def plan_compaction(trajectory, watermark_tokens, open_arcs, retained_beliefs):
    """
    trajectory: list of steps, each {'kind': 'action'|'observation'|'hypothesis'|'conclusion', ...}
    open_arcs: list of arc ids with a pending call or unverified hypothesis
    retained_beliefs: list of {'claim': str, 'falsification_refs': [step_idx], 'evidence_refs': [step_idx]}
    Returns (seam_index, evicted_arc_ids).
    """
    if not trajectory:
        return 0, []

    # Locate the watermark by cumulative token count.
    total = 0
    seam = len(trajectory)
    for i, step in enumerate(trajectory):
        total += step.get("tokens", 0)
        if total >= watermark_tokens:
            seam = i
            break

    # Invariant 1: seam must not fall inside an open reasoning arc.
    for arc_id, (start, end) in open_arcs.items():
        if start <= seam <= end:
            raise CompactionSeamError(
                f"compaction seam at step {seam} falls inside open arc {arc_id} "
                f"[{start},{end}]; defer compaction or spill arc state to ledger"
            )

    # Invariant 2: every retained belief must keep its falsification or evidence set,
    # or be deterministically re-fetchable.
    evicted = set(range(seam))
    for belief in retained_beliefs:
        refs = set(belief.get("falsification_refs", [])) | set(belief.get("evidence_refs", []))
        if refs and refs.issubset(evicted) and not belief.get("refetchable", False):
            raise CompactionSeamError(
                f"retained belief {belief['claim']!r} would lose its entire "
                f"falsification/evidence set {sorted(refs)} to eviction; "
                f"either retain a ref or mark refetchable"
            )

    evicted_arc_ids = [a for a, (s, e) in open_arcs.items() if e < seam]
    return seam, evicted_arc_ids
