# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-hierarchical-auto-compaction-when-the-eviction-frontier-crosses-an-unresolved-tool-call-dependency.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-hierarchical-auto-compaction-when-the-eviction-frontier-crosses-an-unresolved-tool-call-dependency.warrant.json
# Markdown SHA-256:   689d80dad56e435f74f29882826d26ab913aa9f350a8bfd0db582478b696a90e
# Code AST SHA-256:   5b88e3f72a3a2dc462bb879f18d6a988ea141521297584a64729177239c24286
# Verified Classes:   DependencyCrossingEvictionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class DependencyCrossingEvictionError(RuntimeError):
    """Raised when an eviction frontier would sever an unresolved call/result
    or variable-binding dependency between evicted and retained regions."""
    pass


def compact_window(messages, token_budget, hard_capacity):
    """
    messages: list of dicts with keys: role, tokens, tool_call_id (opt),
              pending (bool), defines (set[str]), references (set[str])
    Returns (retained_messages, evicted_messages, digest_inputs).
    Raises DependencyCrossingEvictionError if no dependency-closed frontier
    exists within hard_capacity.
    """
    # 1. Candidate frontier by oldest-first token budget.
    total = sum(m["tokens"] for m in messages)
    if total <= token_budget:
        return messages, [], []

    cumulative = 0
    frontier = 0
    for i, m in enumerate(messages):
        if cumulative + m["tokens"] > token_budget:
            frontier = i
            break
        cumulative += m["tokens"]

    # 2. Open-reference set O across the frontier.
    evicted = messages[:frontier]
    retained = messages[frontier:]

    defined_evicted = set()
    for m in evicted:
        defined_evicted |= m.get("defines", set())
        if m.get("tool_call_id"):
            defined_evicted.add(m["tool_call_id"])

    open_refs = set()
    for m in retained:
        open_refs |= (m.get("references", set()) & defined_evicted)
        if m.get("pending") and m.get("tool_call_id") in defined_evicted:
            open_refs.add(m["tool_call_id"])

    # 3. If closed, evict freely.
    if not open_refs:
        return retained, evicted, evicted

    # 4. Advance frontier to next dependency-closed boundary.
    for j in range(frontier, len(messages)):
        trial_evicted = messages[:j]
        trial_retained = messages[j:]
        trial_defined = set()
        for m in trial_evicted:
            trial_defined |= m.get("defines", set())
            if m.get("tool_call_id"):
                trial_defined.add(m["tool_call_id"])
        trial_open = set()
        for m in trial_retained:
            trial_open |= (m.get("references", set()) & trial_defined)
            if m.get("pending") and m.get("tool_call_id") in trial_defined:
                trial_open.add(m["tool_call_id"])
        if not trial_open:
            projected = sum(m["tokens"] for m in trial_retained)
            if projected <= hard_capacity:
                return trial_retained, trial_evicted, trial_evicted
            break

    # 5. No closed frontier within capacity: refuse to evict.
    raise DependencyCrossingEvictionError(
        f"Cannot compact: open references {sorted(open_refs)} span the eviction "
        f"frontier and no dependency-closed boundary exists within "
        f"hard_capacity={hard_capacity}. Defer compaction or escalate budget."
    )
