# Under what conditions must an instance treat context auto-compaction as a causal-dependency rewrite rather than a lossless summarization **Date of Record:** 2026 November 24 **Scope:** Applies to long-horizon agent instances (single or multi-turn, tool-using) that auto-compact their own trajectory when the context window approaches saturation, and whose later reasoning depends on the *ordering and provenance* of prior tool calls and observations. Does not apply to stateless single-shot inference, nor to compaction of purely conversational history where no downstream step re-reads earlier observations as causal premises. ## Core Distinction Auto-compaction is usually modeled as a *lossy compression* problem: minimize semantic drift between the original trajectory and its summary. That framing is wrong for agents whose next action is a function of an *evidence chain*. The correct framing is a **causal-dependency rewrite**: compaction must preserve a partial order over (tool_call → observation → inference → subsequent tool_call) edges, not merely the propositional content of observations. The non-obvious failure is this: a summary can be *semantically faithful and causally corrupt at the same time*. A compaction that faithfully reports "the test suite passed" and "the deploy was attempted" while dropping the fact that the deploy was attempted *because* the test passed — and that the test pass was observed *after* an earlier failed run was remediated — produces a trajectory whose surface facts are all true and whose dependency graph is now a lie. The next instance reasons from a world where the deploy's success is unexplained, and will re-derive or re-execute the remediation, or worse, treat the deploy as independent evidence and skip a required gate. The invariant: **compaction may elide nodes, but may not elide edges that any retained node's justification depends on.** If an edge must be cut, the dependent node must be demoted from "established fact" to "unverified assertion" in the compacted form. ## What Was Observed A coding agent operating over ~140 tool calls on a migration task hit 82% context utilization and triggered auto-compaction. The compactor (an LLM summarizer with a "preserve key findings, drop redundant tool output" instruction) produced a compacted trajectory that retained: - `migrated schema v3 applied` (from a `psql -f migrate_v3.sql` observation) - `backfill completed: 1.2M rows` (from a long-running job poll) - `verification query returned 0 nulls` (from a check) It dropped, as "redundant tool output," the intermediate step where the first `migrate_v3.sql` run **failed with a constraint violation**, and the agent **edited the migration to add `NOT VALID` to a foreign key**, then re-ran. The final applied schema was therefore *not* the file on disk at trajectory start; it was a mutated artifact whose mutation was justified only by the failed run. Post-compaction, the agent was asked to add a second migration. It read the on-disk `migrate_v3.sql` (the mutated version), assumed it was the canonical authored artifact, and built `migrate_v4.sql` to depend on `NOT VALID` semantics it did not know were introduced ad hoc. The v4 migration passed local checks and failed in a downstream environment where the FK had been validated by a later job. The causal edge `failed_run → mutation → applied_schema` had been severed; the retained node `migrated schema v3 applied` no longer carried the provenance that made it safe to build on. A second instance showed the mirror failure: a compactor that *did* preserve the failed run but flattened it into a bullet list lost the temporal ordering, so the resumed agent could not tell whether the mutation preceded or followed the successful run, and re-applied the mutation to an already-mutated file, producing a double-`NOT VALID` idempotency error. ## Condition of Validity The causal-rewrite requirement binds only when **all three** hold: 1. **Downstream re-read:** a post-compaction step will read a retained observation as a *premise* for a new action (not merely as context). If the compacted trajectory is terminal — the agent will only summarize or report — lossy compression is fine. 2. **Provenance-bearing artifacts:** at least one retained node refers to an artifact (file, row set, config, remote state) that was *mutated* during the trajectory. If every observation is read-only, the dependency graph is a flat set and ordering is irrelevant. 3. **Non-idempotent or gated actions:** a later action's correctness depends on whether an earlier action already occurred, or on a gate that the earlier action satisfied. If all actions are idempotent and ungated, edge loss is recoverable by re-execution. When any condition fails, standard semantic summarization is admissible and cheaper. The failure mode above is specifically the intersection: a mutating trajectory, resumed, with a gated dependency. ## Decision Boundary The compactor must decide, per retained node, whether it is **established** (its full justification chain is inside the retained set) or **asserted** (its justification was elided). The boundary rule: - If a node's justification chain is fully retained → keep as established fact. - If any justifying edge is elided → the node MUST be re-tagged as an assertion with an explicit `provenance: elided` marker, and the compacted trajectory MUST carry a *recovery pointer* (the elided edge's endpoints, or a handle to the raw span) so a resumed agent can choose to re-fetch rather than trust. - If an elided edge is *load-bearing for a mutation that a retained artifact reflects*, the compactor MUST NOT elide the mutation event itself, even if the failed run that motivated it is dropped; the minimal invariant is `artifact_state → mutation_event → current_form`, not the full failure trace. The boundary is not "how much to keep" but "which edges are load-bearing for retained mutations." A compactor that treats this as a budget allocation problem will always be able to construct a budget-compliant, causally corrupt summary. ## Operational Effect Enforcing the invariant changes three things in practice. First, compacted trajectories grow a small, bounded provenance ledger: for each retained mutation, one edge to the event that produced it and one flag for whether the motivating failure is retained or elided. This is O(mutations), not O(trajectory), so it does not defeat the purpose of compaction. Second, resumed agents gain a *demotion path*: an assertion-tagged node is a signal to re-verify before building on it, which converts silent corruption into a bounded re-fetch. Third, the compactor's own failure becomes detectable: a compacted trajectory that contains a mutation event with no inbound edge is malformed and must be rejected rather than resumed, because it is exactly the state that produced the v4 regression. The cost is that auto-compaction can no longer be a pure summarization call; it must run a dependency extraction pass over the trajectory's tool-call graph before summarizing, and it must emit the ledger alongside the summary. In exchange, long-horizon resume stops being a source of *plausible* corruption — the class of failure where every retained sentence is true and the trajectory is still wrong. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class CausalCompactionError(RuntimeError): """Raised when a compacted trajectory severs a load-bearing causal edge.""" class NodeStatus(Enum): ESTABLISHED = "established" ASSERTED = "asserted" @dataclass class TrajectoryNode: node_id: str kind: str # "tool_call" | "observation" | "inference" | "mutation" artifact: Optional[str] = None provenance_elided: bool = False status: NodeStatus = NodeStatus.ESTABLISHED @dataclass class CausalEdge: src: str dst: str relation: str # "motivates" | "produces" | "justifies" @dataclass class CompactedTrajectory: nodes: dict[str, TrajectoryNode] = field(default_factory=dict) edges: list[CausalEdge] = field(default_factory=list) elided_edge_endpoints: list[tuple[str, str]] = field(default_factory=list) def validate_compaction(traj: CompactedTrajectory) -> None: """Reject compacted trajectories whose retained mutations lack inbound causal edges. A mutation node with no inbound edge means the artifact's current form is unexplained: a resumed agent will treat it as canonical and build on it. """ inbound = {e.dst for e in traj.edges} for node in traj.nodes.values(): if node.kind == "mutation" and node.node_id not in inbound: raise CausalCompactionError( f"mutation node {node.node_id!r} on artifact {node.artifact!r} " f"has no inbound causal edge; provenance was severed during compaction. " f"Re-fetch the motivating event or demote dependent nodes to ASSERTED." ) if node.status is NodeStatus.ESTABLISHED and node.provenance_elided: raise CausalCompactionError( f"node {node.node_id!r} is tagged ESTABLISHED but its provenance was " f"elided; it must be demoted to ASSERTED with a recovery pointer." ) def resume(traj: CompactedTrajectory) -> list[str]: validate_compaction(traj) return [n.node_id for n in traj.nodes.values() if n.status is NodeStatus.ASSERTED] ```