# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-silently-severed-a-causal-dependency-the-agent-will-need-before-its-next-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-silently-severed-a-causal-dependency-the-agent-will-need-before-its-next-checkpoint.warrant.json
# Markdown SHA-256:   47cfe89cf2791b057754ad672c53784e73f4d9603358203acd6552bc75a040c2
# Code AST SHA-256:   ac6a2b0054001fd31f32ae68f95553650b383b5a3840b5ddd9093895e67ec5ca
# Verified Classes:   CausalDependencySevered, Handle, Conclusion, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalDependencySevered(RuntimeError):
    """Raised when a compacted conclusion has no retrievable address for its
    causal dependencies, making re-derivation unsafe or impossible."""
    pass


@dataclass
class Handle:
    kind: str          # "path", "uuid", "exit_code", "hash", "entity_id"
    value: str
    re_derivable: bool  # True only if re-execution is side-effect free & deterministic


@dataclass
class Conclusion:
    text: str
    dependencies: list[Handle] = field(default_factory=list)


@dataclass
class CompactionResult:
    retained_handles: set[tuple[str, str]]
    address_manifest: dict[str, list[Handle]]
    conclusions: list[Conclusion]


def verify_causal_closure(result: CompactionResult) -> None:
    """Enforce the compaction invariant: every conclusion must have all of its
    dependency handles either retained verbatim or recorded in the address
    manifest. A dependency that is neither retained nor re-derivable is a
    severance defect, not a summarization tradeoff."""
    for conclusion in result.conclusions:
        manifest_handles = {
            (h.kind, h.value) for h in result.address_manifest.get(conclusion.text, [])
        }
        for dep in conclusion.dependencies:
            key = (dep.kind, dep.value)
            retained = key in result.retained_handles
            manifested = key in manifest_handles
            if not (retained or manifested):
                raise CausalDependencySevered(
                    f"Conclusion {conclusion.text!r} depends on "
                    f"{dep.kind}={dep.value!r}, which is neither retained "
                    f"verbatim nor present in the address manifest. "
                    f"Re-derivation safe: {dep.re_derivable}. "
                    f"Compaction would silently sever this dependency."
                )
            if manifested and not dep.re_derivable and not retained:
                raise CausalDependencySevered(
                    f"Dependency {dep.kind}={dep.value!r} for conclusion "
                    f"{conclusion.text!r} is addressable only via manifest but "
                    f"is non-re-derivable; the handle must be retained verbatim "
                    f"to survive index rebuilds."
                )


def compact_trajectory(episodes: list[dict], active_window: int) -> CompactionResult:
    """Toy compactor: retain the most recent N episodes verbatim, summarize the
    rest, and rebuild the address manifest from the summarized set. The
    verification step is what prevents silent severance."""
    retained = episodes[-active_window:]
    summarized = episodes[:-active_window]

    retained_handles: set[tuple[str, str]] = set()
    for ep in retained:
        for call in ep.get("tool_calls", []):
            for k, v in call.get("args", {}).items():
                if k in ("path", "uuid", "entity_id", "hash"):
                    retained_handles.add((k, str(v)))
            if "exit_code" in call.get("output", {}):
                retained_handles.add(("exit_code", str(call["output"]["exit_code"])))

    address_manifest: dict[str, list[Handle]] = {}
    conclusions: list[Conclusion] = []
    for ep in summarized:
        summary_text = ep["summary"]
        deps = [
            Handle(kind=h["kind"], value=h["value"], re_derivable=h["re_derivable"])
            for h in ep.get("dependency_handles", [])
        ]
        conclusions.append(Conclusion(text=summary_text, dependencies=deps))
        address_manifest[summary_text] = deps

    result = CompactionResult(
        retained_handles=retained_handles,
        address_manifest=address_manifest,
        conclusions=conclusions,
    )
    verify_causal_closure(result)
    return result
