# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/around-what-structural-localization-invariants-must-an-instance-scope-code-mutations-to-prevent-collateral-formatting-and-context-eviction.md # Remnant Warrant: https://corpusfetch.com/c/around-what-structural-localization-invariants-must-an-instance-scope-code-mutations-to-prevent-collateral-formatting-and-context-eviction.warrant.json # Markdown SHA-256: 5a875426aed9d6377602df48b6b73fc1ab97e6c0f58ba53c8574a2dedb3d5255 # Code AST SHA-256: 87c9502cd5a99e7b9dd7ba7f7e2f38943af5a4dd0ae6e79c6dd0ff71801b98da # Verified Classes: LocalizationBoundaryError, SurgicalPatchResult, SurgicalSpanMutator # Defensive Guards: 5 fail-closed invariants (zero external deps) import ast import hashlib import re from dataclasses import dataclass from pathlib import Path from typing import Final class LocalizationBoundaryError(ValueError): '''Raised when a code mutation violates uniqueness, elision, or outer-byte invariants.''' pass @dataclass(frozen=True) class SurgicalPatchResult: file_path: str pre_sha256: str post_sha256: str mutated_line_delta: int class SurgicalSpanMutator: ''' Enforces strict structural localization invariants during code edits: 1. Bans conversational elision placeholders (`... existing code ...`). 2. Requires exact single-occurrence uniqueness (`count == 1`) of the anchor block. 3. Guarantees cryptographic byte-identity of prefix and suffix file regions. 4. Validates Python AST syntax prior to atomic disk commit. ''' ELISION_PATTERNS: Final[tuple[re.Pattern[str], ...]] = ( re.compile(r"(#|//|/\*)\s*\.\.\.\s*(existing|rest of|unchanged|omitted)", re.IGNORECASE), re.compile(r"^\s*\.\.\.\s*$", re.MULTILINE), ) @classmethod def apply_scoped_edit( cls, file_path: Path, *, search_block: str, replace_block: str, validate_python_ast: bool = True, ) -> SurgicalPatchResult: raw_bytes = file_path.read_bytes() pre_hash = hashlib.sha256(raw_bytes).hexdigest() # Preserve dominant line endings uses_crlf = b"\r\n" in raw_bytes original_text = raw_bytes.decode("utf-8") normalized_original = original_text.replace("\r\n", "\n") norm_search = search_block.replace("\r\n", "\n") norm_replace = replace_block.replace("\r\n", "\n") # Gate 1A: Ban elision placeholders for pattern in cls.ELISION_PATTERNS: if pattern.search(norm_replace): raise LocalizationBoundaryError( "Rejected replacement payload: contains elision placeholder that would delete code." ) # Gate 1B: Require exact single match of search anchor occurrences = normalized_original.count(norm_search) if occurrences == 0: raise LocalizationBoundaryError("Search block not found in target file.") if occurrences > 1: raise LocalizationBoundaryError( f"Ambiguous search anchor: matched {occurrences} locations. Expand context lines." ) # Gate 2: Prefix and Suffix byte-identity enforcement idx = normalized_original.index(norm_search) prefix = normalized_original[:idx] suffix = normalized_original[idx + len(norm_search) :] updated_norm = prefix + norm_replace + suffix if not updated_norm.startswith(prefix) or not updated_norm.endswith(suffix): raise LocalizationBoundaryError("Outer prefix/suffix byte-identity invariant violated.") # Gate 4: Pre-commit AST verification if validate_python_ast and file_path.suffix == ".py": try: ast.parse(updated_norm) except SyntaxError as exc: raise LocalizationBoundaryError(f"Post-edit AST syntax error: {exc}") from exc final_text = updated_norm.replace("\n", "\r\n") if uses_crlf else updated_norm final_bytes = final_text.encode("utf-8") file_path.write_bytes(final_bytes) post_hash = hashlib.sha256(final_bytes).hexdigest() delta = norm_replace.count("\n") - norm_search.count("\n") return SurgicalPatchResult(str(file_path), pre_hash, post_hash, delta)