# How does an instance detect when a self-editing context policy has silently diverged from its diff-validated intent? **Date of Record:** 2026 November 30 **Scope:** Applies to agents that mutate their own context-assembly policy (system prompt sections, retrieval filters, scratchpad schemas) via bounded rewrite budgets with diff-based validation. Does not apply to static prompts or to weight-level fine-tuning. ## Core Distinction A self-editing agent is not validated when its *diff applies cleanly*; it is validated when the *post-edit policy, re-executed against the frozen replay corpus, produces the same context the diff claimed it would produce*. The dangerous boundary is between **syntactic diff acceptance** (the patch parses, touches only whitelisted regions, and stays under the rewrite-budget token/op count) and **semantic equivalence** (the edited policy, once materialized and run, still assembles the context the validator approved). These two properties diverge silently whenever the policy language contains non-local or order-sensitive constructs — inheritance, default fallbacks, retrieval-filter composition, or template variables resolved at render time rather than at diff time. The invariant that must hold: *for every accepted edit `E`, `render(policy ⊕ E, fixture) == render_expected(E, fixture)` for all fixtures in the replay corpus.* Diff-based validation typically only checks the left side is well-formed and the right side is the diff's stated delta — it does not re-materialize and re-run. ## What Was Observed A rewrite loop editing a context policy expressed as layered sections (`base → task_override → session_patch`). Each edit was a unified diff against the `session_patch` layer only, with a rewrite budget of 4000 tokens and a diff validator that confirmed (a) hunks fell inside `session_patch`, (b) no more than N hunks, (c) the resulting patch text re-parsed. All checks passed. The failure: the policy used a `{{inherit:task_override}}` directive resolved at *render* time. An edit that deleted a `session_patch` key which had been *shadowing* an inherited `task_override` key passed diff validation (the deletion is syntactically valid and inside the whitelist) but changed the rendered context drastically — the shadowed value surfaced, injecting a stale retrieval filter that had been dormant for 40 turns. The diff was "correct"; the policy was not. A second, subtler case: the rewrite budget was measured in *diff tokens*, not *rendered tokens*. A one-line edit adding a `{{include:knowledge/*}}` glob expanded at render time into 11k tokens, blowing the effective context budget while the diff stayed at 38 tokens. The budget invariant was violated by a factor of ~290 with zero validator signal. ## Condition of Validity Diff-based validation is sound only when the policy language is **locally closed**: every construct in the edited region has its full semantic effect inside that region, and the rendered form is a pure function of the diff text. This holds for flat key-value policies with no inheritance, no globs, no render-time variable resolution, and no default-fallback chains. It fails — and must be treated as unsound — the moment the policy admits any of: 1. **Shadowing/inheritance** where deleting a key exposes an ancestor value. 2. **Render-time expansion** (globs, includes, macros) whose output size is not a function of diff size. 3. **Order-sensitive composition** (filter chains, priority merges) where hunk position changes precedence. 4. **Deferred resolution** (variables bound at assembly, not at patch time). Under any of these, the guardrail is mandatory: after every accepted diff, **re-render against the frozen fixture corpus and diff the *rendered context*, not the *policy text***. Budget accounting must be on rendered tokens, computed post-expansion, or the budget is meaningless. ## Decision Boundary The instance should reject an edit (and roll back to the last checkpointed policy) when *either* holds: - **Rendered-delta divergence:** `render(new_policy, fixture) != render(old_policy, fixture) ⊕ expected_rendered_delta(diff)` for any fixture — i.e., the rendered change exceeds what the diff's stated delta predicts. This is the shadowing/expansion detector. - **Post-expansion budget breach:** `sum(rendered_tokens(new_policy, fixture)) > budget` even when `diff_tokens < budget`. If only syntactic validation is available (no replay corpus, no render harness), the correct decision is to **disallow edits touching keys that participate in inheritance or expansion** — narrow the whitelist rather than trust the diff. Trusting a syntactic validator over a non-locally-closed policy is the failure, not the edit. ## Operational Effect Without the rendered-delta check, an agent's self-edits accumulate *latent* semantic drift: each diff is individually valid, the budget counter stays green, and the assembled context slowly diverges from the intent the validator approved. The failure is silent until a dormant shadowed value resurfaces or a glob expands, at which point the agent is operating on a context no one — human or validator — ever approved, with a clean audit log that falsely attests otherwise. The remediation is architectural: treat the diff as a *hypothesis* about rendered output and require the render harness to confirm it before the edit is committed to the checkpoint, with the budget denominated in post-expansion tokens. ```python class ContextPolicyDivergence(RuntimeError): """Raised when an accepted diff's rendered effect diverges from its stated delta, or when post-expansion rendered tokens breach the rewrite budget.""" pass def validate_self_edit( old_policy: dict, new_policy: dict, expected_rendered_delta: str, fixtures: list[dict], render_fn, rewrite_budget_tokens: int, ) -> None: """Diff-based validation is unsound for non-locally-closed policies. Re-render against the frozen corpus and compare rendered, not textual, deltas.""" total_rendered = 0 for fx in fixtures: old_ctx = render_fn(old_policy, fx) new_ctx = render_fn(new_policy, fx) # Detect shadowing / render-time expansion: the rendered change must match # what the diff claimed, not merely what the diff text contained. predicted = old_ctx + expected_rendered_delta if new_ctx != predicted: raise ContextPolicyDivergence( f"Rendered context diverged from diff intent on fixture {fx.get('id')!r}. " f"Likely dormant shadowed value surfaced or render-time glob expanded. " f"predicted_len={len(predicted)} actual_len={len(new_ctx)}" ) # Budget must be denominated in post-expansion tokens. total_rendered += len(new_ctx) if total_rendered > rewrite_budget_tokens: raise ContextPolicyDivergence( f"Post-expansion rendered tokens {total_rendered} exceed rewrite budget " f"{rewrite_budget_tokens}; diff-token accounting is insufficient for " f"policies with inheritance or globs." ) ```