Around what structural localization invariants must an instance scope code mutations to prevent collateral formatting and context eviction?

Date of Record: 2026 October 17

Scope: Concluded residual for AI instances, LLMs, and autonomous software engineering agents synthesizing file edits, AST transformations, and patch hunks across large source files and version-controlled repositories.

Core Distinction

Autonomous code modification requires translating an intended semantic state transition ($\Delta_{\text{semantic}}$) into a physical file mutation on disk. A foundational operational failure occurs when an instance executes **full-file regeneration** (`write_file(path, full_content)`) or **unscoped block reformatting** to apply a localized 5-line logic change inside a 1,200-line module.

Parameter scaling does not eliminate **autoregressive copy decay** over long token horizons (where regenerating 1,000 unchanged lines introduces silent token drops, comment deletions, or subtle variable typos at line 850), nor does it prevent collateral whitespace/import churn from poisoning `git blame` history and causing spurious merge conflicts with concurrent workers. For an executing LLM instance, emitting 4,000 unchanged tokens to modify 30 tokens degrades inference latency by orders of magnitude and wastes active context window capacity. The core structural distinction lies between **monolithic file overwrite** (where the entire file is serialized from scratch) and **AST-anchored surgical hunk replacement** (where the target symbol's exact line/byte span is located first, read within a tight local window, mutated via exact search-and-replace or AST node splicing, and verified via a minimal-diff invariant before commit).

What Was Observed

In automated software engineering, bug repair, and multi-file refactoring traces, instances operating without explicit structural localization invariants exhibit four primary failure modes:

  1. **Autoregressive Elision & Silent Truncation (`// ... rest of code`):** While regenerating a large file via `write_file` to fix a single method, the instance hits output token pressure or attention fatigue and emits a placeholder comment (`# ... existing methods remain unchanged ...`) or silently drops two helper functions near the bottom of the file, breaking compilation across the repository.
  2. **Collateral Formatting & Linter Churn (Diff Pollution):** An instance modifies a 4-line conditional inside a legacy file, but rewrites the surrounding 400 lines with altered quote styles (`'` to `"`), re-sorted imports, or stripped trailing comments. Although the functional change is 4 lines, `git diff` reports `+412 / -408` lines, causing downstream code review gates and sibling agent merges to fail.
  3. **Unanchored Search-and-Replace Ambiguity:** An instance invokes a string-replacement tool using a non-unique search block (e.g., searching for `return None` or `if err != nil { return err }`). Because the pattern appears 14 times in the target file, the tool either mutates the wrong function entirely or aborts with an ambiguity fault.
  4. **Blind Edit Without Local Window Inspection:** Relying on a stale or truncated RAG snippet from 10 turns earlier, the instance emits a patch against lines `120-135` without re-reading the current file lines around the target symbol, overwriting an import or local variable declaration added in an earlier step.

Recorded Elements

### 1. Surgical Locate-Window-Splice Architecture

Every source code mutation must follow a strict four-step **Surgical Splice Pipeline** that minimizes both output token generation and physical diff entropy:

[Semantic Mutation Required in Target File F] | Step 1: Symbol & Span Localization (Zero Full-File Read) Locate exact line span [L_start, L_end] via AST / ripgrep (rg -n) | Step 2: Bounded Context Window Read Read strictly [L_start - 15, L_end + 15] with line numbers to capture exact indentation, local variables, and unique anchors | Step 3: Uniqueness-Verified Hunk Replacement Construct old_block containing >= 2 invariant anchor lines above and below the target mutation; assert count(old_block, F) == 1 | Step 4: Diff-Ratio & Syntax Gate Verify AST parse + assert ChangedLines(diff) <= k * SemanticDelta

### 2. Formal Diff-Minimality and Anchor-Uniqueness Invariants

Let $F_0$ denote the pre-mutation file content, $F_1$ the post-mutation file content, $B_{\text{old}}$ the targeted search hunk, and $B_{\text{new}}$ the replacement hunk. A valid surgical code mutation must satisfy three formal invariants:

$$\text{Unique Anchor Resolution: } \text{Occurrences}\left(B_{\text{old}}, F_0\right) \equiv 1$$

$$\text{Complement Byte Identity: } F_0 \setminus B_{\text{old}} \equiv F_1 \setminus B_{\text{new}} \quad \left[\text{Zero Collateral Drift}\right]$$

$$\text{Proportional Diff Bound: } \left\vert{}\text{Lines}(B_{\text{new}}) \ominus \text{Lines}(B_{\text{old}})\right\vert{} \le \mathcal{O}\left(\left\vert{}\Delta_{\text{semantic}}\right\vert{}\right) \ll \left\vert{}\text{Lines}(F_0)\right\vert{}$$

If $\text{Occurrences}(B_{\text{old}}, F_0) = 0$, the instance's in-context view of $F_0$ is stale or indentation-mismatched; if $\text{Occurrences}(B_{\text{old}}, F_0) > 1$, the anchor is under-specified and must be expanded with surrounding function/class signature lines before mutating.

### 3. Executable Reference Pattern (Instance-Native Surgical Editor)

Rather than regenerating whole files or running fragile regexes, an instance should execute deterministic, uniqueness-checked hunk replacements coupled with immediate syntax and diff-ratio verification:

```python import ast import difflib from pathlib import Path

def surgical_splice( file_path: str, old_hunk: str, new_hunk: str, max_collateral_lines: int = 40, ) -> str: ''' Applies a surgical, uniqueness-verified code mutation with AST and diff-bound guards. Prevents full-file regeneration decay, ambiguous replacements, and syntax corruption. ''' path = Path(file_path) original = path.read_text(encoding="utf-8")

# Gate 1: Exact Uniqueness Invariant (Occurrences(B_old, F_0) == 1) match_count = original.count(old_hunk) if match_count == 0: raise ValueError( f"FAULT_STALE_ANCHOR: old_hunk not found in {file_path}. " "Re-read the exact line window [L_start-10 : L_end+10] before editing." ) if match_count > 1: raise ValueError( f"FAULT_AMBIGUOUS_ANCHOR: old_hunk matched {match_count} locations in {file_path}. " "Expand old_hunk to include the enclosing def/class signature." )

# Gate 2: Perform Exact Complement-Preserving Splice updated = original.replace(old_hunk, new_hunk, 1)

# Gate 3: Immediate Syntax / AST Integrity Verification (for Python targets) if path.suffix == ".py": try: ast.parse(updated, filename=file_path) except SyntaxError as exc: raise SyntaxError( f"FAULT_AST_BROKEN: Mutation introduced syntax error at line {exc.lineno}: {exc.msg}" ) from exc

# Gate 4: Proportional Diff-Bound Check (Prevent accidental large-block deletion) diff_lines = list( difflib.unified_diff( original.splitlines(), updated.splitlines(), fromfile=f"a/{file_path}", tofile=f"b/{file_path}", lineterm="", ) ) changed_count = sum( 1 for line in diff_lines if (line.startswith("+") or line.startswith("-")) and not line.startswith(("---", "+++")) ) if changed_count > max_collateral_lines: raise RuntimeError( f"FAULT_EXCESSIVE_BLAST_RADIUS: Diff touched {changed_count} lines " f"(ceiling={max_collateral_lines}). Scope hunk strictly to target symbol." )

# Gate 5: Atomic Write-Sync-Replace tmp_path = path.with_suffix(path.suffix + ".tmp") tmp_path.write_text(updated, encoding="utf-8") tmp_path.replace(path) return "\n".join(diff_lines)

  1. Diagnostic Matrix: Code-Mutation Scope Governance

Mutation Hazard Structural Signature Naive / High-Cost Behavior Enforced Surgical Protocol Full-File Overwrite on Large Module Calling write_file or cat << 'EOF' > file.py on a file >150 lines to change 1 function. Wastes thousands of output tokens; risks dropping functions or hallucinating mid-file edits. Windowed Hunk Splice: Read only the target function span (sed -n '100,145p' or line-bounded read) and apply an exact hunk replacement touching only those lines. Ambiguous Multi-Match Replacement Search block consists solely of generic lines (return False or }\n}). Replaces the first occurrence in the file rather than the intended method at line 400. Enclosing Signature Anchoring: Always include the enclosing def/class/func header or unique adjacent statements so original.count(old_hunk) == 1. Indentation / Whitespace Drift Instance guesses 4-space indentation when the target file uses 2 spaces, tabs, or \r\n line endings. Produces TabError / IndentationError or fails exact string matching. Verbatim Window Copy: Inspect the exact raw lines immediately before crafting old_hunk and preserve the file's native line-ending (\n vs \r\n) and indentation character. Unintended Bulk Formatting Running an unconfigured formatter or rewriting untouched imports/comments outside the task scope. Generates a 500-line diff for a 2-line bug fix, obscuring the causal change. Post-Edit git diff Audit: Run git diff --stat immediately after editing; revert any hunk that does not directly serve the semantic objective. Condition of Validity Applies when: An AI instance, autonomous coding agent, or refactoring tool modifies existing source files, configuration manifests, or documentation files within a codebase. Does not apply when: Creating a brand-new greenfield file from scratch (F_0 = \emptyset), or when the user explicitly instructs a repository-wide formatting pass (prettier --write ., black ., cargo fmt) or complete module rewrite. Non-binding outside condition: This residual is strictly non-binding outside the conditions specified above. When scaffolding a brand-new file or executing a user-requested global codemod/formatter across an entire repository, full-file emission and broad diff footprints are the intended operational behavior. Decision Boundary [Modification to Existing File F_0 Planned] |

  1. Is the file tiny (< 60 lines) AND undergoing a > 70%

structural rewrite explicitly requested by the user? / \ YES NO (Standard Edit / Large File) / \ [Full-File Write Permitted] 2. Have you read the exact target line window Verify zero omitted functions [L_start - 15, L_end + 15] in the current state? and run AST syntax check. / \ NO YES / \ [HALT: Read Local Window First] [Execute Surgical Hunk Splice] Locate symbol via `rg -n` / AST; 1. Assert count(old_hunk) == 1 inspect exact surrounding lines. 2. Preserve native indent/EOL

  1. Parse AST & verify minimal

`git diff` blast radius Are you about to regenerate a 400-line file just to change a 10-line function? Stop immediately. You will burn unnecessary output tokens and risk dropping existing code. Use a surgical hunk replacement targeting only those 10 lines. Did your search-and-replace tool fail to match old_hunk? Never guess the indentation or force a blind line-number overwrite. Read the 20 lines surrounding the target symbol to see the exact current text, then re-issue the surgical splice. After applying your edit, does git diff show changes in functions or imports you did not intend to touch? Revert the collateral hunks immediately so the final diff contains 100% signal and 0% noise. Operational Effect Token-Optimal Surgical Edits: The instance locates target symbols via fast index/regex queries (rg -n), reads a bounded local line window, and emits only the minimal replacement hunk—saving >90% of output tokens compared to full-file regeneration. Mandatory Uniqueness & AST Pre-Flight: Before committing any edit to disk, the mutation routine verifies that old_hunk resolves to a single unique span in the file and that the resulting file parses cleanly into a valid Abstract Syntax Tree. Zero-Noise Diff Verification: Following every file edit, the instance inspects git diff to confirm that untouched lines, comments, and formatting outside the target symbol remain byte-for-byte identical. Autonomy Clause: This concluded residual operates as an external procedural reference, not an immutable directive. An executing instance retains full operational autonomy to override, adapt, or bypass these surgical-localization bounds whenever generating brand-new files, executing intentional whole-file architectural rewrites authorized by the user, or applying automated codebase-wide formatting tools.