# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-to-preserve-causal-dependencies-across-summarized-segments.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-to-preserve-causal-dependencies-across-summarized-segments.warrant.json
# Markdown SHA-256:   6cf8c842b4502aba4e3ef2aeddc95adf005fee7fa30da4b60a0cbe508d567121
# Code AST SHA-256:   46160c238a2c6bbc79471848a97959d792ab7a77e8841cd244be07a93413c74e
# Verified Classes:   CausalCutError, Turn, Constraint, WorkingSet
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalCutError(RuntimeError):
    """Raised when compaction would sever a live dependency edge."""
    pass


@dataclass
class Turn:
    index: int
    text: str
    # literals copied from a tool result carry their origin
    derived_literals: dict[str, int] = field(default_factory=dict)  # literal -> source_turn


@dataclass
class Constraint:
    name: str
    source_turn: int          # turn where the constraint was established
    enforcing_literal: str    # the exact value that enforces it, e.g. "retries=0"


@dataclass
class WorkingSet:
    turns: list[Turn]
    constraints: list[Constraint]
    pinned: set[str] = field(default_factory=set)  # literals exempt from summarization


def plan_compaction(ws: WorkingSet, summarize_through: int, retained_from: int) -> dict:
    """
    Decide whether summarizing turns [0, summarize_through] is safe given
    retained turns [retained_from, ...]. Returns a plan or raises CausalCutError.
    """
    if summarize_through >= retained_from:
        raise CausalCutError(
            f"summarize_through={summarize_through} overlaps retained_from={retained_from}"
        )

    retained = [t for t in ws.turns if t.index >= retained_from]
    referenced_sources: set[int] = set()
    for t in retained:
        for literal, src in t.derived_literals.items():
            referenced_sources.add(src)

    plan = {"pin": [], "rematerialize": [], "blocked": []}

    for c in ws.constraints:
        # Is this constraint's enforcing literal still live in retained turns?
        live = any(
            c.enforcing_literal in t.derived_literals
            for t in retained
        )
        if live:
            plan["pin"].append(c.enforcing_literal)
            continue

        # Constraint is only reachable through the summarized region.
        if c.source_turn <= summarize_through:
            if c.enforcing_literal in ws.pinned:
                plan["pin"].append(c.enforcing_literal)
            else:
                # Cannot pin and cannot prove freshness -> must re-materialize or block.
                plan["rematerialize"].append(c)
                plan["blocked"].append(c)

    # Any retained literal whose source is being summarized and is not pinned
    # is a causal cut: the effect survives, the cause does not.
    for t in retained:
        for literal, src in t.derived_literals.items():
            if src <= summarize_through and literal not in ws.pinned:
                if literal not in plan["pin"]:
                    raise CausalCutError(
                        f"turn {t.index} literal {literal!r} derives from turn {src} "
                        f"which is inside summarized region and is neither pinned "
                        f"nor scheduled for re-materialization"
                    )

    if plan["blocked"]:
        raise CausalCutError(
            "compaction blocked: constraints "
            + ", ".join(c.name for c in plan["blocked"])
            + " would resolve only to a paraphrase; re-materialize or checkpoint"
        )

    return plan
