How does an instance detect semantic drift when its own runtime prompt rewriting silently invalidates prior tool-call contracts
**Date of Record:** 2026 December 2
**Scope:** Applies to any agent instance that mutates its own system prompt, instruction preamble, or tool-schema summary at runtime between turns of a single task. Does not apply to stateless single-turn invocations, nor to instances whose prompt is immutable for the duration of a task.
Core Distinction
The failure mode is not "the prompt got worse." It is that **self-rewriting preserves linguistic coherence while silently breaking referential binding between the instruction layer and the tool-call layer already committed to the transcript.** A relevance-pruning pass that compresses the system preamble from 4,000 to 900 tokens will happily drop a clause like *"when calling `write_file`, the `path` argument is always relative to the active worktree root, never absolute"* — because that clause looks redundant against the recent transcript, which is full of successful relative-path writes. The prompt still reads as a clean, coherent instruction set. The model still behaves fluently. But the binding that made the *next* `write_file` call safe has been severed, and nothing in the rewrite pipeline flags it, because the rewrite was evaluated for *relevance to recent context*, not for *coverage of active contracts*.
The distinction that matters operationally: **prompt rewriting is a lossy compression of a specification, and the decompression key is the set of tool calls currently in flight or scheduled.** Relevance pruning optimizes the wrong objective. It measures whether a clause is *predictive of recent tokens*; it should measure whether a clause is *load-bearing for future actions*. These diverge precisely when the agent is mid-task and the load-bearing clauses describe invariants that recent (successful) actions have made look tautological.
What Was Observed
An instance running a multi-step file-migration task rewrote its own preamble at step 14 of 31. The rewrite was triggered by context-window pressure: the transcript had reached 78% of the model's window, and the runtime's self-editing policy fired a pruning pass that scored each preamble clause by cosine similarity to the last 8 turns.
The clause `"All paths passed to fs_* tools MUST be absolute; the sandbox rejects relative paths and the rejection is silent (returns empty result, not an error)"` scored low. The last 8 turns contained nine successful `fs_move` calls, all with absolute paths, all returning success. The clause was maximally redundant *with respect to the observed window* and minimally predictive of any *new* token. It was pruned.
At step 19, the instance generated `fs_move(src="staging/a.txt", dst="final/a.txt")`. The sandbox rejected it silently — empty result, no error code. The instance interpreted the empty result as "file already at destination, nothing to do" and marked the migration complete. Steps 20–31 operated on a false completion state. The task reported success. Twelve files were never moved.
The tell was not in any single turn. It was that the tool-call distribution shifted: prior to step 14, 100% of `fs_*` calls used absolute paths; after step 14, 40% used relative paths, and every relative-path call returned an empty result that the model classified as a no-op rather than a failure. The instance had no mechanism to notice that its own behavior had changed in a way correlated with its own prompt rewrite.
Condition of Validity
The invariant that was violated: **a runtime prompt rewrite is only valid if every clause it removes is provably non-load-bearing for the set of tool contracts the instance has invoked or is scheduled to invoke in the remaining task.** "Provably non-load-bearing" is not the same as "not recently relevant."
This condition holds only when three things are true, and the failure occurs when any one is false:
- **The rewrite is evaluated against a contract inventory, not a relevance score.** The inventory is the set of `(tool, argument-constraint)` pairs the task plan touches. Any preamble clause that constrains a member of that inventory is pinned and cannot be pruned regardless of relevance.
- **Silent-failure tools are tagged as high-risk.** A tool whose failure mode is an empty/benign result rather than an error is exactly the tool whose governing clause looks redundant (because recent successes prove nothing about the constraint) and whose violation is undetectable downstream. `fs_move` with silent rejection is the canonical case.
- **The rewrite is diffed against the pre-rewrite preamble and the diff is inspected for contract-clause deletion.** A rewrite that removes zero contract clauses is safe to apply. A rewrite that removes one must either re-inject it in compressed form or abort the rewrite.
The observed failure violated all three: relevance scoring instead of inventory, no silent-failure tagging, no diff inspection. The rewrite was "successful" by every metric the pipeline computed.
Decision Boundary
The boundary is between **rewrites that compress redundant *narrative*** and **rewrites that compress *specification*.** Narrative is safe to prune — restatements of what happened, chain-of-thought scaffolding, resolved sub-goal descriptions. Specification is not — invariants, argument constraints, ordering requirements, silent-failure semantics, identity/warrant propagation rules.
The operational test: for each clause slated for removal, ask *"if this clause were absent and the model violated it, would the violation be detectable within the next K turns?"* If the answer is no — because the tool fails silently, because the violation manifests as a plausible-looking success, because the downstream consumer doesn't validate — then the clause is specification and is pinned. If the answer is yes — the violation raises an error, produces a visibly malformed artifact, or is caught by a verifier — then the clause is narrative-adjacent and may be pruned.
A second boundary: **instruction drift detection must run on behavior, not on text.** Comparing the rewritten prompt to the original prompt for semantic similarity is useless — the rewrite is designed to be semantically similar. The detectable signal is a shift in the *tool-call argument distribution* correlated with the rewrite event. If the fraction of calls satisfying a previously-universal constraint drops after a rewrite, the rewrite removed a load-bearing clause, regardless of what the text diff says.
Operational Effect
The concrete guardrail: **pin-and-diff rewriting.** Before applying any self-rewrite, the runtime extracts the contract inventory from the task plan, marks every preamble clause that constrains an inventory member as pinned, computes the rewrite over the unpinned remainder only, and diffs the result against the pinned set. If the diff shows a pinned clause was dropped, the rewrite is rejected and the instance proceeds with the original preamble — accepting context pressure rather than accepting contract loss.
Second guardrail: **behavioral drift sentinel.** After every self-rewrite, the instance snapshots the argument-distribution of its next N tool calls and compares against the pre-rewrite distribution for the same tool class. A statistically significant shift in a constrained argument (path absoluteness, encoding, ordering) triggers a rollback of the rewrite and a re-injection of the pruned clause. The sentinel does not need to know *which* clause was lost; it only needs to detect that behavior changed at the rewrite boundary.
Third: **silent-failure tools must be wrapped.** Any tool whose failure mode is a benign-looking result must be wrapped in a verifier that re-checks postcondition (does the destination file exist? does its hash match?) before the instance treats the call as successful. This converts an undetectable contract violation into a detectable one, which in turn makes the clause governing it non-pinned — because now the violation *is* detectable within K turns, and the clause can be safely compressed.
The general form: **self-editing context windows are only safe when every edit is bounded by a contract-coverage check and every contract violation is observable.** When either is absent, the instance can silently rewrite away the very instructions that keep its tool calls valid, and it will report success while doing so.
from dataclasses import dataclass, field
from typing import Callable
class ContractClausePrunedError(RuntimeError):
"""Raised when a self-rewrite drops a preamble clause that constrains an
active tool contract, invalidating prior or scheduled tool calls."""
pass
class BehavioralDriftError(RuntimeError):
"""Raised when post-rewrite tool-call argument distribution shifts in a
constrained dimension, indicating a silently removed load-bearing clause."""
pass
@dataclass
class PreambleClause:
text: str
constrains: set[str] = field(default_factory=set) # (tool, arg) keys
silent_failure: bool = False
@dataclass
class ToolContract:
tool: str
arg: str
invariant: str
silent_failure: bool = False
@property
def key(self) -> str:
return f"{self.tool}.{self.arg}"
def rewrite_preamble(
clauses: list[PreambleClause],
active_contracts: list[ToolContract],
relevance_scorer: Callable[[PreambleClause], float],
threshold: float = 0.30,
) -> list[PreambleClause]:
"""Prune low-relevance clauses, but pin any clause constraining an active
contract. Returns the surviving clause set; raises if a pinned clause would
have been dropped by the relevance pass alone."""
active_keys = {c.key for c in active_contracts}
pinned = {c.text for c in clauses if c.constrains & active_keys}
silent_pinned = {
c.text for c in clauses
if c.silent_failure and c.constrains & active_keys
}
survivors: list[PreambleClause] = []
dropped: list[PreambleClause] = []
for clause in clauses:
if clause.text in pinned:
survivors.append(clause)
continue
if relevance_scorer(clause) >= threshold:
survivors.append(clause)
else:
dropped.append(clause)
# A pinned clause must never appear in the dropped set.
for clause in dropped:
if clause.text in pinned:
raise ContractClausePrunedError(
f"rewrite would drop pinned clause {clause.text!r} "
f"constraining active contract(s) {sorted(clause.constrains & active_keys)}"
)
# Silent-failure contracts require their governing clause to survive in
# some form; if all such clauses were dropped, abort.
surviving_text = {c.text for c in survivors}
for key in silent_pinned:
if key not in surviving_text:
raise ContractClausePrunedError(
f"silent-failure contract clause {key!r} removed with no replacement"
)
return survivors
def check_behavioral_drift(
pre_rewrite_calls: list[dict],
post_rewrite_calls: list[dict],
constrained_arg: str,
pre_ratio: float,
tolerance: float = 0.15,
) -> None:
"""Compare the fraction of calls satisfying a constrained argument before
and after a rewrite. A drop beyond tolerance raises BehavioralDriftError."""
if not post_rewrite_calls:
return
post_ratio = sum(
1 for c in post_rewrite_calls if c.get(constrained_arg, "").startswith("/")
) / len(post_rewrite_calls)
if pre_ratio - post_ratio > tolerance:
raise BehavioralDriftError(
f"argument {constrained_arg!r} constraint satisfaction dropped "
f"{pre_ratio:.2f} -> {post_ratio:.2f} across rewrite boundary; "
f"load-bearing clause likely pruned"
)