# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-goal-drift-when-auto-compaction-rewrites-the-head-of-a-long-horizon-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-goal-drift-when-auto-compaction-rewrites-the-head-of-a-long-horizon-trajectory.warrant.json
# Markdown SHA-256:   c694cb7c8fa83f002db46000d4bb64ccabc1f82c723d6ecf66d651514e776fa7
# Code AST SHA-256:   17ca57db86989866a5634dc0f39da0fdc1ff20f180664cbff02cdbbf62f0e41e
# Verified Classes:   GoalDriftError, Span, Trajectory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Provenance = Literal["instruction", "derived", "raw"]


class GoalDriftError(RuntimeError):
    """Raised when compaction would launder a derived summary into instruction authority."""


@dataclass
class Span:
    text: str
    provenance: Provenance
    compaction_depth: int = 0


@dataclass
class Trajectory:
    pinned_instruction: str          # byte-exact, external source of truth
    spans: list[Span] = field(default_factory=list)
    max_compaction_depth: int = 1

    def compact_head(self, keep_tail: int) -> list[Span]:
        head = self.spans[:-keep_tail] if keep_tail else list(self.spans)
        tail = self.spans[-keep_tail:] if keep_tail else []
        compacted: list[Span] = []

        for span in head:
            # Invariant 1: instruction spans are never summarized.
            if span.provenance == "instruction":
                raise GoalDriftError(
                    "instruction span entered compactable head; "
                    "pin it out-of-band and re-inject verbatim"
                )
            # Invariant 2: bound summary-of-summary depth.
            new_depth = span.compaction_depth + 1
            if new_depth > self.max_compaction_depth:
                raise GoalDriftError(
                    f"span at compaction_depth={span.compaction_depth} would "
                    f"exceed max={self.max_compaction_depth}; re-derive from raw"
                )
            # Summaries are always tagged derived, never promoted.
            compacted.append(
                Span(
                    text=f"[summary d{new_depth}] {span.text[:120]}",
                    provenance="derived",
                    compaction_depth=new_depth,
                )
            )

        # Invariant 3: pinned instruction is re-injected each cycle, byte-exact.
        head_anchor = Span(text=self.pinned_instruction, provenance="instruction")
        self.spans = [head_anchor, *compacted, *tail]
        return self.spans

    def assert_goal_integrity(self) -> None:
        instr = [s for s in self.spans if s.provenance == "instruction"]
        if len(instr) != 1 or instr[0].text != self.pinned_instruction:
            raise GoalDriftError(
                "goal integrity violated: pinned instruction missing or mutated"
            )


def run_compaction_cycle(traj: Trajectory, keep_tail: int) -> None:
    traj.compact_head(keep_tail=keep_tail)
    traj.assert_goal_integrity()  # fail closed before next reasoning step
