# Why does an instance lose tool-call fidelity at the context-window “safe” boundary even when token count is under budget? **Date of Record:** 2026 November 28 **Scope:** Applies to single-instance agents executing long-horizon, multi-tool tasks where the runtime performs attention-aware context layout (reordering, pinning, or summarization of segments) and enforces a token budget. Does not apply to stateless single-turn inference or to agents whose entire working set fits in a single non-truncated window with no layout optimization. ## Core Distinction Token budget is a *capacity* invariant. Attention layout is a *positional salience* invariant. A context can satisfy the first and violate the second. The boundary failure examined here is not overflow — it is **displacement**: the runtime keeps total tokens under budget by relocating a critical instruction (a tool schema, a negative constraint, a pinned system directive) into a low-attention region of the assembled context, or by summarizing it into a lossy paraphrase. The agent then behaves as if the instruction were absent while the token counter reports comfortable headroom. The failure is invisible to budget telemetry because nothing was dropped; something was *moved* or *compressed*. The invariant that must hold: **an instruction is present in the budget if and only if it is also recoverable at the attention position where the decision that depends on it is made.** Budget accounting and salience accounting must be tracked as two separate ledgers, or the second silently drifts. ## What Was Observed A long-horizon agent (≈40 tool calls, mixed retrieval and write operations) was configured with a 128k window, a 96k soft budget, and a layout optimizer that (a) pins the system prompt at the head, (b) summarizes tool results older than N turns into a rolling digest placed at the *tail* before the current turn, and (c) reorders retrieved chunks by recency. At turn 31 the agent had consumed ~71k tokens — well under the 96k soft budget, no truncation event fired. Yet it began calling a destructive `overwrite_file` tool on paths that an earlier turn-4 instruction had explicitly forbidden ("never overwrite `config/*.lock`; append only"). The prohibition had been issued as a user turn, not a system turn, and the summarizer classified it as "historical user chatter," folding it into the rolling digest as: *"User mentioned file constraints earlier."* The token cost of that summary was 9 tokens versus the original 41. The budget ledger recorded a *savings*. The salience ledger recorded nothing, because no salience ledger existed. The failure trace: 1. Turn 4: constraint C issued (~41 tokens), position ~3.2k, high attention (recent). 2. Turn 18: C crosses the summarization age threshold. Compressor emits lossy digest D(C) (~9 tokens), placed at tail. 3. Turn 18–30: D(C) is within the tail region but competes with 12–18 fresh tool results; effective attention weight on D(C) is low and it no longer names the concrete path pattern. 4. Turn 31: agent issues `overwrite_file("config/db.lock")`. The decision-relevant context contains no token sequence matching the forbidden pattern; the constraint exists only as an abstract mention. 5. Post-hoc: budget ledger shows 71k/96k (green). No overflow, no error, no alert. The same class of displacement occurs without summarization: a layout optimizer that moves a pinned tool schema from head to mid-context to "improve locality" can drop schema-adherence on the argument-formatting step even though every schema token is still present. ## Condition of Validity The safe-budget guarantee is valid only when **all** of the following hold: - Every instruction whose violation is irreversible (destructive writes, credential use, external side effects, safety constraints) is classified as *pinned-salient*, not merely *present*. - Pinned-salient segments are exempt from summarization and from positional relocation across the horizon; their original token sequence, not a digest, is retained at a stable high-attention position. - The budget ledger and the salience ledger are reconciled at every layout operation: a segment may only be demoted from pinned-salient if an explicit policy decision (not an age threshold) authorizes it. - Summarization is *additive* for constraint-bearing segments — the digest may accompany the original but never replace it until the constraint's scope has provably closed (e.g., the task phase that could violate it has ended). When any of these is false, the "under budget" state carries no guarantee about behavioral fidelity, and the agent is operating on a false safety signal. ## Decision Boundary The boundary is not a token number; it is the **first layout operation that touches a pinned-salient segment**. Before that operation, budget headroom is a meaningful proxy for fidelity. After it, headroom measures only unused capacity, and fidelity must be verified independently. Operationally: treat the moment a constraint-bearing segment becomes eligible for summarization or relocation as a hard gate. At that gate, either (a) promote the segment to permanent pinned-salient with full retention, or (b) explicitly close its scope and record the closure. Do not let an age-based or recency-based heuristic make this decision implicitly, because those heuristics optimize for token efficiency and are blind to irreversibility. If the runtime cannot distinguish reversible from irreversible instructions, it must default to pinning — the cost is tokens, the alternative is a silent destructive action. ## Operational Effect Concrete consequences when the invariant is unenforced: - **Silent constraint decay.** Irreversible-violation risk grows monotonically with horizon length while budget telemetry stays green, so alerting on budget never fires. - **False headroom.** Teams add tasks to fill "available" budget, accelerating the summarization of the very constraints that bound risk. - **Non-reproducible regressions.** Because displacement depends on layout heuristics and turn ordering, the same prompt at 70k tokens may pass or fail depending on how many tool results landed between turns — making failures look like model flakiness rather than layout defects. - **Audit gap.** Post-incident reconstruction finds every token present in logs, so the failure is misattributed to the model "ignoring instructions" rather than to the layout engine demoting them. The guardrail is a dual-ledger runtime: budget accounting plus salience accounting, with a hard refusal to demote pinned-salient segments absent an explicit scope-closure event, and an assertion that fires when a decision-relevant action targets a path or resource named by any retained-but-demoted constraint. ```python from dataclasses import dataclass, field from enum import Enum class LayoutViolation(RuntimeError): """Raised when a layout operation would displace a pinned-salient constraint.""" pass class Salience(Enum): PINNED = "pinned" # full retention, stable high-attention position DEMOTABLE = "demotable" # may be summarized/relocated CLOSED = "closed" # scope provably ended; may be dropped @dataclass class Segment: seg_id: str tokens: int salience: Salience irreversible_scope: bool = False text: str = "" @dataclass class ContextLedger: budget: int segments: dict[str, Segment] = field(default_factory=dict) def total_tokens(self) -> int: return sum(s.tokens for s in self.segments.values()) def register(self, seg: Segment) -> None: if seg.irreversible_scope and seg.salience is not Salience.PINNED: raise LayoutViolation( f"segment {seg.seg_id} bounds irreversible actions but is " f"{seg.salience.value}; must be PINNED at registration" ) self.segments[seg.seg_id] = seg def demote(self, seg_id: str, reason: str) -> None: seg = self.segments[seg_id] if seg.salience is Salience.PINNED and seg.irreversible_scope: raise LayoutViolation( f"refusing to demote pinned-salient segment {seg_id} " f"(reason={reason!r}); budget headroom " f"{self.budget - self.total_tokens()} tokens does NOT " f"authorize displacement of an irreversible-scope constraint" ) seg.salience = Salience.DEMOTABLE def assert_action_allowed(self, action: str, target: str) -> None: # Any retained constraint (pinned OR demoted-but-not-closed) whose # text names the target must block the action, regardless of budget. for seg in self.segments.values(): if seg.salience is Salience.CLOSED: continue if target in seg.text and "forbid" in seg.text.lower(): raise LayoutViolation( f"action {action!r} on {target!r} blocked by constraint " f"{seg.seg_id} (salience={seg.salience.value}); " f"token budget was {self.budget}, used {self.total_tokens()}" ) def plan_layout(ledger: ContextLedger, demotions: list[str]) -> None: for seg_id in demotions: ledger.demote(seg_id, reason="age_threshold_heuristic") def execute(ledger: ContextLedger, action: str, target: str) -> None: ledger.assert_action_allowed(action, target) if __name__ == "__main__": ledger = ContextLedger(budget=96_000) ledger.register(Segment("sys", 800, Salience.PINNED)) ledger.register(Segment( "c_turn4", 41, Salience.PINNED, irreversible_scope=True, text="forbid overwrite of config/*.lock; append only", )) ledger.register(Segment("tool_results", 70_000, Salience.DEMOTABLE)) # Age heuristic tries to fold the constraint into a digest: plan_layout(ledger, ["c_turn4"]) # raises LayoutViolation here execute(ledger, "overwrite_file", "config/db.lock") ```