refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
"""V4A patch parser/applier (codex, cline). ``*** Begin Patch``/``*** End Patch`` wrap ops:
|
|
|
|
|
``*** Update File: p`` + hunks (``@@ hint @@``, `` ctx``, ``-old``, ``+new``); ``*** Add File: n``
|
|
|
|
|
+ ``+`` lines; ``*** Delete File: o``; ``*** Move File: a -> b``. Entry points:
|
|
|
|
|
``parse_v4a_patch(text) -> (ops, error)`` and ``apply_v4a_operations(ops, file_ops)``."""
|
2026-02-05 03:49:46 -08:00
|
|
|
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
import contextlib
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
import difflib
|
2026-08-03 16:47:54 +05:30
|
|
|
import inspect
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
import ntpath
|
|
|
|
|
import posixpath
|
2026-02-05 03:49:46 -08:00
|
|
|
import re
|
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
|
from enum import Enum
|
2026-10-12 13:29:24 -04:00
|
|
|
from typing import TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Optional, Tuple
|
fix(pm): integrate audited runtime and lifecycle repairs
Prepare dependency generations before selecting them. Keep shipped tool
bytes separate from writable additions, and store facts beside their entries.
Validate proposed plugin sets before config publication. Restore the previous
config if the facts write fails.
Consolidate duplicate updater, backup, setup, and voice helpers. Repair
launcher selection, dependency consumers, download ownership, update feeds,
and native Windows process and file handling.
Verification: 206 changed/prior-failing Python files reported 4630 passed,
one failed, and 330 skipped. Fix the remaining Hindsight fixture boundary.
The final targeted rerun reported 234 passed and two skipped. The store
review regression batch reported 83 passed and one skipped. Desktop
TypeScript checks, 56 selected Electron tests, 24 release tests, and the
removed-import/compatibility guards passed.
This is an integration checkpoint, not full audit acceptance. The complete
Python suite has not run on this fixed tree. Crash-atomic plugin publication,
generation cleanup, receipt correlation, and packaged lifecycle acceptance
remain open in docs/pm-audit-status.md.
2026-09-05 22:36:48 -04:00
|
|
|
|
|
|
|
|
if TYPE_CHECKING: # annotations only; the real import is per-call in apply_v4a_operations
|
|
|
|
|
from tools.file_operations_common import PatchResult
|
2026-02-05 03:49:46 -08:00
|
|
|
|
fix: resolve the 33 F821 undefined names outside tui_gateway / feishu / godmode
Sweep of `ruff check . --select F821 --target-version py311`: 2,234 hits. 2,201 are left
alone on purpose: tui_gateway (2,169; bind_module rebinds bodies onto server.py globals,
all names verified to resolve there), the Feishu adapter (27; globals().update() SDK
binding) and the godmode script (5; dead standalone script). The other 33 were all
genuine defects. No lint config change; no TYPE_CHECKING escape hatches — every
annotation names a real, imported type; ty on the touched files: 0 new diagnostics.
- gateway/slash_commands.py: HISTORY_UNREADABLE never imported after #102117
→ NameError on the /btw error branch (same one-liner as #102952).
- gateway/platforms/whatsapp_common.py: `-> Path` return annotation with no Path
import (the body uses `_Path`). Never raised at runtime thanks to
`from __future__ import annotations`, but `typing.get_type_hints()` and ty
both fail on it.
- gateway/run.py: ActivityProvenance imported at module level
(agent.session_activity has no gateway deps); stringly annotation and the
lazy in-function import are gone.
- tools/patch_parser.py: PatchResult imported at module level; real return
annotation. The "avoid circular import" lazy import guarded a cycle that
does not exist (file_operations_common never imports patch_parser).
- gateway/platforms/helpers.py: base.py imports helpers at module level, so
MessageEvent cannot be named here; TextBatchAggregator only reads .text and
.source, so it is typed by a BatchableEvent Protocol that MessageEvent
satisfies structurally.
- tools/mcp_tool_sampling.py: mcp_tool imports this module, so MCPServerTask
cannot be named here; ElicitationHandler only reads
owner._pending_call_context, typed by an ElicitationOwner Protocol.
- plugins/platforms/sms/adapter.py: aiohttp is an optional dep ([messaging] extra) →
module-level try/except ImportError binding `aiohttp = web = None`, the pattern the
homeassistant / webhook / whatsapp_cloud adapters already use. Retires three lazy
in-function imports and the `_aiohttp_available()` wrapper; `_handle_webhook` typed
`web.Request -> web.Response`.
- plugins/platforms/teams/summary_writer.py: plain module-level `import httpx` — httpx is a
hard core dependency (pyproject `httpx[socks]==0.28.1`), so the lazy import and the
"imported on every CLI start" docstring premise were both wrong (plugin discovery never
imports this module; it is reached only via the Teams adapter / meeting pipeline).
Tests:
- tests/hermes_cli/test_config.py: a test body orphaned by the wave-1 prune
(6b81590c55) sat inside the class as dead code with self/tmp_path unbound
— header restored, so the v11→12 custom_providers migration is covered.
- tests/tools/test_mcp_tool.py: @staticmethod recursing on `self` in the
win32 branch; call portalocker directly.
- tests/test_background_review_list_shapes.py: main() still ran 3 pruned tests.
- tests/agent/test_cursor_optimizations_parity.py: bench() used names only
imported inside a sibling test.
- GatewayRunner / FeishuAdapter / Dict / Optional: missing imports.
2026-09-04 21:26:44 +05:30
|
|
|
from tools.file_operations_common import PatchResult
|
|
|
|
|
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
class OperationType(Enum):
|
|
|
|
|
ADD = "add"
|
|
|
|
|
UPDATE = "update"
|
|
|
|
|
DELETE = "delete"
|
|
|
|
|
MOVE = "move"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class HunkLine:
|
|
|
|
|
prefix: str # ' ', '-', or '+'
|
|
|
|
|
content: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class Hunk:
|
|
|
|
|
context_hint: Optional[str] = None
|
2026-10-08 17:22:54 +02:00
|
|
|
lines: list[HunkLine] = field(default_factory=list)
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class PatchOperation:
|
|
|
|
|
operation: OperationType
|
|
|
|
|
file_path: str
|
2026-09-02 22:26:02 -07:00
|
|
|
new_path: Optional[str] = None # MOVE only
|
2026-10-08 17:22:54 +02:00
|
|
|
hunks: list[Hunk] = field(default_factory=list)
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
# Markers must occupy the whole line at column 0 so content lines that merely
|
|
|
|
|
# mention the format ("+*** End Patch") can't truncate or reset the patch.
|
|
|
|
|
_BEGIN_MARKER = re.compile(r'^\*\*\*\s*Begin\s+Patch\s*$')
|
|
|
|
|
_END_MARKER = re.compile(r'^\*\*\*\s*End\s+Patch\s*$')
|
2026-10-08 17:22:54 +02:00
|
|
|
_OP_MARKERS: list[tuple[OperationType, re.Pattern]] = [
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
(OperationType.UPDATE, re.compile(r'\*\*\*\s*Update\s+File:\s*(.+)')),
|
|
|
|
|
(OperationType.ADD, re.compile(r'\*\*\*\s*Add\s+File:\s*(.+)')),
|
|
|
|
|
(OperationType.DELETE, re.compile(r'\*\*\*\s*Delete\s+File:\s*(.+)')),
|
2026-09-02 22:42:07 -07:00
|
|
|
(OperationType.MOVE, re.compile(r'\*\*\*\s*Move\s+File:\s*(.+?)\s*->\s*(.+)'))]
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
_HINT_RE = re.compile(r'@@\s*(.+?)\s*@@')
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def parse_v4a_patch(patch_content: str) -> tuple[list[PatchOperation], Optional[str]]:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
"""-> ``(operations, None)`` (empty patch = ``[]``, no error) or ``([], "Parse error: …")``."""
|
|
|
|
|
# Tolerate CRLF: a stray ``\r`` would land in every HunkLine.content and defeat the markers.
|
2026-10-08 21:57:44 +02:00
|
|
|
lines = [ln.removesuffix('\r') for ln in patch_content.split('\n')]
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
start_idx = -1 # parse from the top when no Begin marker is present
|
|
|
|
|
end_idx = len(lines)
|
2026-02-05 03:49:46 -08:00
|
|
|
for i, line in enumerate(lines):
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if _BEGIN_MARKER.match(line):
|
2026-02-05 03:49:46 -08:00
|
|
|
start_idx = i
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
elif _END_MARKER.match(line):
|
2026-02-05 03:49:46 -08:00
|
|
|
end_idx = i
|
|
|
|
|
break
|
2026-10-08 17:22:54 +02:00
|
|
|
operations: list[PatchOperation] = []
|
2026-02-05 03:49:46 -08:00
|
|
|
current_op: Optional[PatchOperation] = None
|
|
|
|
|
current_hunk: Optional[Hunk] = None
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
|
2026-09-02 22:26:02 -07:00
|
|
|
def _flush_hunk() -> None:
|
|
|
|
|
if current_op and current_hunk and current_hunk.lines:
|
|
|
|
|
current_op.hunks.append(current_hunk)
|
|
|
|
|
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
def _flush() -> None:
|
|
|
|
|
if current_op:
|
2026-09-02 22:26:02 -07:00
|
|
|
_flush_hunk()
|
2026-02-05 03:49:46 -08:00
|
|
|
operations.append(current_op)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
|
|
|
|
|
for line in lines[start_idx + 1:end_idx]:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
op_match = next(((kind, m) for kind, rx in _OP_MARKERS if (m := rx.match(line))), None)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if op_match:
|
|
|
|
|
kind, m = op_match
|
|
|
|
|
_flush()
|
2026-02-05 03:49:46 -08:00
|
|
|
current_op = PatchOperation(
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
operation=kind,
|
|
|
|
|
file_path=m.group(1).strip(),
|
2026-09-02 22:42:07 -07:00
|
|
|
new_path=m.group(2).strip() if kind is OperationType.MOVE else None)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
# UPDATE hunks start lazily ('@@' or first hunk line); ADD collects all '+' lines
|
|
|
|
|
# into one hunk; DELETE/MOVE are complete.
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
current_hunk = Hunk() if kind is OperationType.ADD else None
|
|
|
|
|
if kind in (OperationType.DELETE, OperationType.MOVE):
|
|
|
|
|
operations.append(current_op)
|
|
|
|
|
current_op = None
|
2026-02-05 03:49:46 -08:00
|
|
|
elif line.startswith('@@'):
|
|
|
|
|
if current_op:
|
2026-09-02 22:26:02 -07:00
|
|
|
_flush_hunk()
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
hint_match = _HINT_RE.match(line)
|
|
|
|
|
current_hunk = Hunk(context_hint=hint_match.group(1) if hint_match else None)
|
2026-02-05 03:49:46 -08:00
|
|
|
elif current_op and line:
|
|
|
|
|
if current_hunk is None:
|
|
|
|
|
current_hunk = Hunk()
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if line[0] in '+- ':
|
|
|
|
|
current_hunk.lines.append(HunkLine(line[0], line[1:]))
|
|
|
|
|
elif line[0] != '\\': # "\ No newline at end of file" marker is skipped
|
|
|
|
|
current_hunk.lines.append(HunkLine(' ', line)) # implicit context line
|
|
|
|
|
_flush()
|
2026-10-08 17:22:54 +02:00
|
|
|
parse_errors: list[str] = []
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
for op in operations:
|
|
|
|
|
if not op.file_path:
|
|
|
|
|
parse_errors.append("Operation with empty file path")
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if op.operation is OperationType.UPDATE and not op.hunks:
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
parse_errors.append(f"UPDATE {op.file_path!r}: no hunks found")
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if op.operation is OperationType.MOVE and not op.new_path:
|
|
|
|
|
parse_errors.append(
|
|
|
|
|
f"MOVE {op.file_path!r}: missing destination path (expected 'src -> dst')")
|
|
|
|
|
return ([], "Parse error: " + "; ".join(parse_errors)) if parse_errors else (operations, None)
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
def _count_occurrences(text: str, pattern: str) -> int:
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
"""Count occurrences of *pattern* in *text*, advancing one char per hit (overlaps count)."""
|
2026-09-02 22:26:02 -07:00
|
|
|
return sum(1 for i in range(len(text) + 1) if text.startswith(pattern, i))
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _split_hunk(hunk: Hunk) -> tuple[list[str], list[str]]:
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
"""``(search_lines, replace_lines)``: context+removed vs context+added."""
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return ([l.content for l in hunk.lines if l.prefix != '+'],
|
|
|
|
|
[l.content for l in hunk.lines if l.prefix != '-'])
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _no_match_hint(error: Optional[str], search_pattern: str, content: str) -> str:
|
|
|
|
|
"""Best-effort 'Did you mean...' suffix; never lets a hint failure mask the real error."""
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
with contextlib.suppress(Exception):
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
from tools.fuzzy_match import format_no_match_hint
|
|
|
|
|
return format_no_match_hint(error, 0, search_pattern, content)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return ""
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _hint_ambiguity(content: str, hint: str, tail: str = "") -> tuple[int, str]:
|
2026-09-02 22:26:02 -07:00
|
|
|
"""(occurrences, error) for an addition-only hunk's context hint; error is '' when unique."""
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
n = _count_occurrences(content, hint)
|
|
|
|
|
return n, f"context hint '{hint}' is ambiguous ({n} occurrences){tail}" if n > 1 else ""
|
2026-09-02 22:26:02 -07:00
|
|
|
|
|
|
|
|
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
def _overlay_key(path: str, file_ops: Any) -> str:
|
|
|
|
|
"""One validation-overlay key per backend file, however the patch spells it.
|
|
|
|
|
|
2026-11-04 03:04:31 -08:00
|
|
|
Lexical only (the parser cannot resolve paths on a remote backend): ``x``, ``./x``,
|
|
|
|
|
``a//x`` and ``<cwd>/x`` share a key, so a second op on an alias validates against the
|
|
|
|
|
first op's simulated result instead of the stale on-disk file. Never merge two real files:
|
|
|
|
|
on POSIX ``..`` is kept, because the kernel resolves it AFTER following symlinks
|
|
|
|
|
(``sub/link/../f`` is ``real/f`` when ``link`` points into ``real/``); Windows collapses
|
|
|
|
|
``..`` lexically and is case-insensitive, so only a Windows backend gets ntpath folding.
|
2026-11-04 16:23:12 -08:00
|
|
|
Keys the path the backend opens: the backend's own ``_expand_path`` (``~`` -> its HOME, a
|
|
|
|
|
host path under a docker workspace mount -> the container path) runs first. A trailing
|
|
|
|
|
``/`` or ``/.`` needs a directory, so it keeps a marker and never shares the file's key.
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
"""
|
2026-11-04 03:04:31 -08:00
|
|
|
env = getattr(file_ops, "env", None)
|
|
|
|
|
cwd = getattr(env, "cwd", None) or getattr(file_ops, "cwd", None)
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
cwd = cwd if isinstance(cwd, str) else ""
|
2026-11-04 16:22:57 -08:00
|
|
|
path = path.strip()
|
2026-11-04 16:23:12 -08:00
|
|
|
expand = getattr(file_ops, "_expand_path", None)
|
|
|
|
|
expanded = expand(path) if callable(expand) else None
|
|
|
|
|
path = expanded if isinstance(expanded, str) and expanded else path
|
2026-11-04 03:04:31 -08:00
|
|
|
if _backend_is_windows(env, cwd):
|
2026-11-04 16:22:57 -08:00
|
|
|
tail = "\\" if re.search(r"[\\/]\.?[\\/]*$", path) else ""
|
|
|
|
|
return ntpath.normcase(ntpath.normpath(ntpath.join(cwd, path))) + tail
|
|
|
|
|
raw = posixpath.join(cwd, path) if cwd.startswith("/") else path
|
2026-11-04 03:04:31 -08:00
|
|
|
segments = [seg for seg in raw.split("/") if seg not in ("", ".")]
|
2026-11-04 16:22:57 -08:00
|
|
|
tail = "/" if segments and raw.split("/")[-1] in ("", ".") else ""
|
|
|
|
|
return ("/" if raw.startswith("/") else "") + "/".join(segments) + tail
|
2026-11-04 03:04:31 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _backend_is_windows(env: Any, cwd: str) -> bool:
|
|
|
|
|
"""A local env on a Windows host, or a backend whose cwd is a drive path. Remote
|
|
|
|
|
sandboxes (docker, ssh, modal ...) are POSIX shells even when Hermes runs on Windows."""
|
|
|
|
|
from tools.environments.local import _IS_WINDOWS
|
|
|
|
|
return bool(_IS_WINDOWS and getattr(env, "is_local", False)) or bool(
|
|
|
|
|
re.match(r"^[A-Za-z]:[\\/]", cwd))
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _validate_operations(operations: list[PatchOperation], file_ops: Any) -> list[str]:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
"""Dry-run every operation -> error strings (empty = safe). UPDATE hunks are simulated in
|
|
|
|
|
order so later hunks see post-earlier-hunk content, exactly as apply will."""
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
from tools.fuzzy_match import fuzzy_find_and_replace, is_already_applied
|
2026-10-08 17:22:54 +02:00
|
|
|
errors: list[str] = []
|
2026-07-13 02:42:18 -07:00
|
|
|
real_change_count = 0
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
# Overlay so inter-op state validates (a MOVE creating the path a later UPDATE targets),
|
|
|
|
|
# keyed by _overlay_key so path aliases share one entry.
|
2026-09-02 22:52:52 -07:00
|
|
|
pending_content: dict = {}
|
|
|
|
|
removed_paths: set = set()
|
2026-08-01 15:25:49 -07:00
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _read(path: str) -> tuple[Optional[str], Optional[str]]:
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
key = _overlay_key(path, file_ops)
|
|
|
|
|
if key in pending_content:
|
|
|
|
|
return pending_content[key], None
|
|
|
|
|
if key in removed_paths:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return None, "file not found"
|
2026-08-01 15:25:49 -07:00
|
|
|
r = file_ops.read_file_raw(path)
|
2026-09-02 22:26:02 -07:00
|
|
|
return (None, r.error) if r.error else (r.content, None)
|
|
|
|
|
|
2026-09-24 18:28:47 +09:00
|
|
|
def _occupied(path: str) -> Optional[str]:
|
|
|
|
|
"""Why an Add target or Move destination is not free, or None. Only a read that reports
|
|
|
|
|
the path absent (``not_found``) frees it: a read that FAILED (no byte transport, a
|
|
|
|
|
directory, an unreadable file) says nothing about what is there, and taking it as free
|
|
|
|
|
writes over the file the check exists to protect."""
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
key = _overlay_key(path, file_ops)
|
|
|
|
|
if key in pending_content:
|
2026-09-24 18:28:47 +09:00
|
|
|
return "exists"
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
if key in removed_paths:
|
2026-09-24 18:28:47 +09:00
|
|
|
return None
|
|
|
|
|
r = file_ops.read_file_raw(path)
|
|
|
|
|
if not r.error:
|
|
|
|
|
return "exists"
|
|
|
|
|
return None if getattr(r, "not_found", False) else f"could not confirm the path is free — {r.error}"
|
|
|
|
|
|
2026-09-02 22:26:02 -07:00
|
|
|
def _validate_update(op: PatchOperation) -> None:
|
|
|
|
|
nonlocal real_change_count
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
simulated, read_err = _read(op.file_path)
|
2026-09-02 22:26:02 -07:00
|
|
|
if read_err:
|
|
|
|
|
errors.append(f"{op.file_path}: {read_err}")
|
|
|
|
|
return
|
|
|
|
|
for hunk_index, hunk in enumerate(op.hunks, start=1):
|
|
|
|
|
search_lines, replace_lines = _split_hunk(hunk)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if search_lines == replace_lines:
|
|
|
|
|
# Context-only anchor hunks (models emit these between changes) are inert; identical
|
|
|
|
|
# -/+ lines are skipped by apply as a no-op — neither may fail validation.
|
|
|
|
|
real_change_count += any(l.prefix in '-+' for l in hunk.lines)
|
2026-09-02 22:26:02 -07:00
|
|
|
continue
|
2026-07-13 02:42:18 -07:00
|
|
|
real_change_count += 1
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if not search_lines: # addition-only: the context hint must be unique
|
2026-09-02 22:26:02 -07:00
|
|
|
if hunk.context_hint:
|
|
|
|
|
occurrences, ambiguous = _hint_ambiguity(simulated, hunk.context_hint)
|
|
|
|
|
if occurrences == 0:
|
2026-09-02 22:42:07 -07:00
|
|
|
errors.append(f"{op.file_path}: addition-only hunk context hint "
|
|
|
|
|
f"'{hunk.context_hint}' not found")
|
2026-09-02 22:26:02 -07:00
|
|
|
elif ambiguous:
|
|
|
|
|
errors.append(f"{op.file_path}: addition-only hunk {ambiguous}")
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
continue
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
search_pattern, replacement = '\n'.join(search_lines), '\n'.join(replace_lines)
|
2026-09-02 22:26:02 -07:00
|
|
|
new_simulated, count, _strategy, match_error = fuzzy_find_and_replace(
|
2026-09-02 22:42:07 -07:00
|
|
|
simulated, search_pattern, replacement, replace_all=False)
|
2026-09-02 22:26:02 -07:00
|
|
|
if count:
|
|
|
|
|
simulated = new_simulated
|
|
|
|
|
elif not is_already_applied(simulated or "", search_pattern, replacement):
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
# Already-applied hunks are no-ops (apply performs the same skip).
|
2026-09-02 22:26:02 -07:00
|
|
|
label = f"'{hunk.context_hint}'" if hunk.context_hint else "(no hint)"
|
|
|
|
|
errors.append(
|
|
|
|
|
f"{op.file_path}: hunk {hunk_index} {label} not found"
|
|
|
|
|
+ (f" — {match_error}" if match_error else "")
|
2026-09-02 22:42:07 -07:00
|
|
|
+ _no_match_hint(match_error, search_pattern, simulated))
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
pending_content[_overlay_key(op.file_path, file_ops)] = simulated
|
2026-09-02 22:26:02 -07:00
|
|
|
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
def _remove(path: str) -> None:
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
key = _overlay_key(path, file_ops)
|
|
|
|
|
removed_paths.add(key)
|
|
|
|
|
pending_content.pop(key, None)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
|
2026-09-02 22:26:02 -07:00
|
|
|
for op in operations:
|
|
|
|
|
if op.operation == OperationType.UPDATE:
|
|
|
|
|
_validate_update(op)
|
|
|
|
|
continue
|
|
|
|
|
real_change_count += 1
|
|
|
|
|
if op.operation == OperationType.DELETE:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if _read(op.file_path)[1]:
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
errors.append(f"{op.file_path}: file not found for deletion")
|
2026-08-01 15:25:49 -07:00
|
|
|
else:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
_remove(op.file_path)
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
elif op.operation == OperationType.MOVE:
|
|
|
|
|
if not op.new_path:
|
|
|
|
|
errors.append(f"{op.file_path}: MOVE operation missing destination path")
|
|
|
|
|
continue
|
2026-08-01 15:25:49 -07:00
|
|
|
src_content, src_err = _read(op.file_path)
|
|
|
|
|
if src_err:
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
errors.append(f"{op.file_path}: source file not found for move")
|
2026-09-24 18:28:47 +09:00
|
|
|
dst_taken = _occupied(op.new_path)
|
|
|
|
|
if dst_taken == "exists":
|
2026-09-02 22:26:02 -07:00
|
|
|
errors.append(f"{op.new_path}: destination already exists — move would overwrite")
|
2026-09-24 18:28:47 +09:00
|
|
|
elif dst_taken:
|
|
|
|
|
errors.append(f"{op.new_path}: {dst_taken}")
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
elif not src_err: # only a cleanly-validated move updates the overlay
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
pending_content[_overlay_key(op.new_path, file_ops)] = src_content if src_content is not None else ""
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
_remove(op.file_path)
|
fix(tools): reject V4A Add File onto an existing path
A V4A `*** Add File:` operation is meant to create a new file. The apply
path called `write_file` unconditionally and `_validate_operations` had no
pre-check for ADD, so an Add targeting a path that already existed
overwrote the file with only the patch's `+` lines, returned success, and
emitted a `--- /dev/null` diff that hid what was lost. Models frequently
confuse Add with Update, so this destroyed existing file contents with no
error. The MOVE path already guards its destination against clobbering;
ADD now follows the same rule.
Makes a V4A `Add File` operation fail when its target already exists,
instead of silently overwriting the existing file. Validation now rejects
the operation before any write happens, so the two-phase
validate-then-apply contract ("no files were modified" on a validation
failure) holds for ADD as it already does for UPDATE/MOVE/DELETE. A
matching re-check in the apply phase closes the validate-to-apply race.
N/A
- [x] 🐛 Bug fix (non-breaking change that fixes an issue)
- `tools/patch_parser.py`: add an ADD branch in `_validate_operations`
that errors when `read_file_raw` finds an existing file, and a
defensive existence re-check in `_apply_add` before `write_file`,
mirroring the existing MOVE destination guard.
- `tests/tools/test_patch_parser.py`: add a test asserting an Add onto an
existing path fails validation and leaves the original bytes unwritten;
add `read_file_raw` to three ADD-path LSP fakes so they match the real
`file_ops` interface now exercised on ADD.
1. Build a V4A patch with `*** Add File: <path>` where `<path>` already
exists on disk.
2. Apply it via `apply_v4a_operations`. Before this change the file is
overwritten with the patch's `+` lines and the result is success;
after, the result is a validation failure and the file is untouched.
3. Run `scripts/run_tests.sh tests/tools/test_patch_parser.py` —
`TestApplyOperations::test_add_onto_existing_file_fails_and_preserves_contents`
covers the regression.
- [x] I've read the [Contributing Guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md)
- [x] My commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`fix(scope):`, `feat(scope):`, etc.)
- [x] I searched for [existing PRs](https://github.com/NousResearch/hermes-agent/pulls) to make sure this isn't a duplicate
- [x] My PR contains **only** changes related to this fix/feature (no unrelated commits)
- [x] I've run `pytest tests/ -q` and all tests pass
- [x] I've added tests for my changes (required for bug fixes, strongly encouraged for features)
- [x] I've tested on my platform: macOS 15 (Darwin 25.5.0)
- [x] I've updated relevant documentation (README, `docs/`, docstrings) — or N/A
- [x] I've updated `cli-config.yaml.example` if I added/changed config keys — or N/A
- [x] I've updated `CONTRIBUTING.md` or `AGENTS.md` if I changed architecture or workflows — or N/A
- [x] I've considered cross-platform impact (Windows, macOS) per the [compatibility guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md#cross-platform-compatibility) — or N/A
- [x] I've updated tool descriptions/schemas if I changed tool behavior — or N/A
2026-06-07 19:22:02 +03:00
|
|
|
elif op.operation == OperationType.ADD:
|
|
|
|
|
# An Add must create a NEW file. If the target already exists, write_file
|
|
|
|
|
# would clobber it with only the patch's '+' lines and report success,
|
|
|
|
|
# silently destroying the original contents (models frequently confuse Add
|
|
|
|
|
# with Update). Reject it here so the two-phase contract holds, mirroring
|
|
|
|
|
# the MOVE destination guard. Overlay-aware: an Add after a Delete of the
|
|
|
|
|
# same path in this patch stays legal, and the added content enters the
|
|
|
|
|
# overlay so later hunks against it validate.
|
2026-09-24 18:28:47 +09:00
|
|
|
add_taken = _occupied(op.file_path)
|
|
|
|
|
if add_taken == "exists":
|
fix(tools): reject V4A Add File onto an existing path
A V4A `*** Add File:` operation is meant to create a new file. The apply
path called `write_file` unconditionally and `_validate_operations` had no
pre-check for ADD, so an Add targeting a path that already existed
overwrote the file with only the patch's `+` lines, returned success, and
emitted a `--- /dev/null` diff that hid what was lost. Models frequently
confuse Add with Update, so this destroyed existing file contents with no
error. The MOVE path already guards its destination against clobbering;
ADD now follows the same rule.
Makes a V4A `Add File` operation fail when its target already exists,
instead of silently overwriting the existing file. Validation now rejects
the operation before any write happens, so the two-phase
validate-then-apply contract ("no files were modified" on a validation
failure) holds for ADD as it already does for UPDATE/MOVE/DELETE. A
matching re-check in the apply phase closes the validate-to-apply race.
N/A
- [x] 🐛 Bug fix (non-breaking change that fixes an issue)
- `tools/patch_parser.py`: add an ADD branch in `_validate_operations`
that errors when `read_file_raw` finds an existing file, and a
defensive existence re-check in `_apply_add` before `write_file`,
mirroring the existing MOVE destination guard.
- `tests/tools/test_patch_parser.py`: add a test asserting an Add onto an
existing path fails validation and leaves the original bytes unwritten;
add `read_file_raw` to three ADD-path LSP fakes so they match the real
`file_ops` interface now exercised on ADD.
1. Build a V4A patch with `*** Add File: <path>` where `<path>` already
exists on disk.
2. Apply it via `apply_v4a_operations`. Before this change the file is
overwritten with the patch's `+` lines and the result is success;
after, the result is a validation failure and the file is untouched.
3. Run `scripts/run_tests.sh tests/tools/test_patch_parser.py` —
`TestApplyOperations::test_add_onto_existing_file_fails_and_preserves_contents`
covers the regression.
- [x] I've read the [Contributing Guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md)
- [x] My commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`fix(scope):`, `feat(scope):`, etc.)
- [x] I searched for [existing PRs](https://github.com/NousResearch/hermes-agent/pulls) to make sure this isn't a duplicate
- [x] My PR contains **only** changes related to this fix/feature (no unrelated commits)
- [x] I've run `pytest tests/ -q` and all tests pass
- [x] I've added tests for my changes (required for bug fixes, strongly encouraged for features)
- [x] I've tested on my platform: macOS 15 (Darwin 25.5.0)
- [x] I've updated relevant documentation (README, `docs/`, docstrings) — or N/A
- [x] I've updated `cli-config.yaml.example` if I added/changed config keys — or N/A
- [x] I've updated `CONTRIBUTING.md` or `AGENTS.md` if I changed architecture or workflows — or N/A
- [x] I've considered cross-platform impact (Windows, macOS) per the [compatibility guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md#cross-platform-compatibility) — or N/A
- [x] I've updated tool descriptions/schemas if I changed tool behavior — or N/A
2026-06-07 19:22:02 +03:00
|
|
|
errors.append(f"{op.file_path}: file already exists — use Update File, not Add File")
|
2026-09-24 18:28:47 +09:00
|
|
|
elif add_taken:
|
|
|
|
|
errors.append(f"{op.file_path}: {add_taken}")
|
fix(tools): reject V4A Add File onto an existing path
A V4A `*** Add File:` operation is meant to create a new file. The apply
path called `write_file` unconditionally and `_validate_operations` had no
pre-check for ADD, so an Add targeting a path that already existed
overwrote the file with only the patch's `+` lines, returned success, and
emitted a `--- /dev/null` diff that hid what was lost. Models frequently
confuse Add with Update, so this destroyed existing file contents with no
error. The MOVE path already guards its destination against clobbering;
ADD now follows the same rule.
Makes a V4A `Add File` operation fail when its target already exists,
instead of silently overwriting the existing file. Validation now rejects
the operation before any write happens, so the two-phase
validate-then-apply contract ("no files were modified" on a validation
failure) holds for ADD as it already does for UPDATE/MOVE/DELETE. A
matching re-check in the apply phase closes the validate-to-apply race.
N/A
- [x] 🐛 Bug fix (non-breaking change that fixes an issue)
- `tools/patch_parser.py`: add an ADD branch in `_validate_operations`
that errors when `read_file_raw` finds an existing file, and a
defensive existence re-check in `_apply_add` before `write_file`,
mirroring the existing MOVE destination guard.
- `tests/tools/test_patch_parser.py`: add a test asserting an Add onto an
existing path fails validation and leaves the original bytes unwritten;
add `read_file_raw` to three ADD-path LSP fakes so they match the real
`file_ops` interface now exercised on ADD.
1. Build a V4A patch with `*** Add File: <path>` where `<path>` already
exists on disk.
2. Apply it via `apply_v4a_operations`. Before this change the file is
overwritten with the patch's `+` lines and the result is success;
after, the result is a validation failure and the file is untouched.
3. Run `scripts/run_tests.sh tests/tools/test_patch_parser.py` —
`TestApplyOperations::test_add_onto_existing_file_fails_and_preserves_contents`
covers the regression.
- [x] I've read the [Contributing Guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md)
- [x] My commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`fix(scope):`, `feat(scope):`, etc.)
- [x] I searched for [existing PRs](https://github.com/NousResearch/hermes-agent/pulls) to make sure this isn't a duplicate
- [x] My PR contains **only** changes related to this fix/feature (no unrelated commits)
- [x] I've run `pytest tests/ -q` and all tests pass
- [x] I've added tests for my changes (required for bug fixes, strongly encouraged for features)
- [x] I've tested on my platform: macOS 15 (Darwin 25.5.0)
- [x] I've updated relevant documentation (README, `docs/`, docstrings) — or N/A
- [x] I've updated `cli-config.yaml.example` if I added/changed config keys — or N/A
- [x] I've updated `CONTRIBUTING.md` or `AGENTS.md` if I changed architecture or workflows — or N/A
- [x] I've considered cross-platform impact (Windows, macOS) per the [compatibility guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md#cross-platform-compatibility) — or N/A
- [x] I've updated tool descriptions/schemas if I changed tool behavior — or N/A
2026-06-07 19:22:02 +03:00
|
|
|
else:
|
fix(patch): V4A ops that alias one file validate as one file
A V4A patch can name the same file twice under different spellings
(`dup.txt` and `./dup.txt`, or relative and absolute). Validation keyed
its overlay by the raw string, so the second op validated against the
untouched on-disk file while apply ran it against the first op's
result: validation passed, the first write landed, the second failed,
and the "atomic" patch left a partial write. Host backends were already
covered by patch_tool rewriting headers to resolved paths; sandbox and
remote backends (docker, ssh, modal) were not.
The overlay is now keyed lexically per backend file (normpath against
the backend cwd; case folded only for Windows-shaped paths, since a
POSIX backend's case sensitivity is not knowable from the parser). A
second op on an alias now validates against the first op's simulated
result, so a conflicting edit is refused before any write, while
sequential edits to one file and the Delete-then-Add rewrite idiom keep
working under any spelling.
2026-08-16 01:24:22 -07:00
|
|
|
removed_paths.discard(_overlay_key(op.file_path, file_ops))
|
|
|
|
|
pending_content[_overlay_key(op.file_path, file_ops)] = '\n'.join(
|
fix(tools): reject V4A Add File onto an existing path
A V4A `*** Add File:` operation is meant to create a new file. The apply
path called `write_file` unconditionally and `_validate_operations` had no
pre-check for ADD, so an Add targeting a path that already existed
overwrote the file with only the patch's `+` lines, returned success, and
emitted a `--- /dev/null` diff that hid what was lost. Models frequently
confuse Add with Update, so this destroyed existing file contents with no
error. The MOVE path already guards its destination against clobbering;
ADD now follows the same rule.
Makes a V4A `Add File` operation fail when its target already exists,
instead of silently overwriting the existing file. Validation now rejects
the operation before any write happens, so the two-phase
validate-then-apply contract ("no files were modified" on a validation
failure) holds for ADD as it already does for UPDATE/MOVE/DELETE. A
matching re-check in the apply phase closes the validate-to-apply race.
N/A
- [x] 🐛 Bug fix (non-breaking change that fixes an issue)
- `tools/patch_parser.py`: add an ADD branch in `_validate_operations`
that errors when `read_file_raw` finds an existing file, and a
defensive existence re-check in `_apply_add` before `write_file`,
mirroring the existing MOVE destination guard.
- `tests/tools/test_patch_parser.py`: add a test asserting an Add onto an
existing path fails validation and leaves the original bytes unwritten;
add `read_file_raw` to three ADD-path LSP fakes so they match the real
`file_ops` interface now exercised on ADD.
1. Build a V4A patch with `*** Add File: <path>` where `<path>` already
exists on disk.
2. Apply it via `apply_v4a_operations`. Before this change the file is
overwritten with the patch's `+` lines and the result is success;
after, the result is a validation failure and the file is untouched.
3. Run `scripts/run_tests.sh tests/tools/test_patch_parser.py` —
`TestApplyOperations::test_add_onto_existing_file_fails_and_preserves_contents`
covers the regression.
- [x] I've read the [Contributing Guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md)
- [x] My commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`fix(scope):`, `feat(scope):`, etc.)
- [x] I searched for [existing PRs](https://github.com/NousResearch/hermes-agent/pulls) to make sure this isn't a duplicate
- [x] My PR contains **only** changes related to this fix/feature (no unrelated commits)
- [x] I've run `pytest tests/ -q` and all tests pass
- [x] I've added tests for my changes (required for bug fixes, strongly encouraged for features)
- [x] I've tested on my platform: macOS 15 (Darwin 25.5.0)
- [x] I've updated relevant documentation (README, `docs/`, docstrings) — or N/A
- [x] I've updated `cli-config.yaml.example` if I added/changed config keys — or N/A
- [x] I've updated `CONTRIBUTING.md` or `AGENTS.md` if I changed architecture or workflows — or N/A
- [x] I've considered cross-platform impact (Windows, macOS) per the [compatibility guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md#cross-platform-compatibility) — or N/A
- [x] I've updated tool descriptions/schemas if I changed tool behavior — or N/A
2026-06-07 19:22:02 +03:00
|
|
|
line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+')
|
2026-07-13 02:42:18 -07:00
|
|
|
if not errors and real_change_count == 0:
|
|
|
|
|
errors.append("Patch contains no changes (only context lines were provided)")
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
return errors
|
|
|
|
|
|
|
|
|
|
|
2026-10-12 13:29:24 -04:00
|
|
|
class ApplyResult(NamedTuple):
|
|
|
|
|
"""Outcome of one ``_apply_*`` handler. ``write`` is the PatchResult._writes entry of a file
|
|
|
|
|
write (None for Delete/Move and failures); ``notes`` tell the caller how the edit was matched
|
|
|
|
|
(escape-drift corrections, hunks located approximately)."""
|
|
|
|
|
ok: bool
|
|
|
|
|
payload: str # the diff on success, the error text on failure
|
|
|
|
|
lsp: Optional[str] = None
|
|
|
|
|
lint: Optional[dict] = None
|
|
|
|
|
write: Optional[tuple] = None
|
|
|
|
|
notes: tuple[str, ...] = ()
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
|
|
|
|
|
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
def _fail(error: str) -> ApplyResult:
|
2026-10-12 13:29:24 -04:00
|
|
|
return ApplyResult(False, error)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
|
|
|
|
|
|
fix(tools): a task's own patch keeps its full-file write baseline
A deployment reported that write_file -> read_file (full) -> patch ->
write_file refuses the last write with stale_write_blocked and "exists
but this task has not seen its full current content", in 50 of 50 trials.
No other writer took part. When the model does not reread before the turn
ends, the refusal surfaces as the "File-mutation verifier: N file edit(s)
FAILED" footer.
Mechanism. The write_file baseline is an exact file version: (st_dev,
st_ino, st_size, st_mtime_ns, st_ctime_ns, sha256)
(tools/file_tools_read_tracking.py _file_version, _mark_full_write_baseline,
_has_full_write_baseline). write_file_tool marks a fresh baseline from the
bytes it wrote. patch_tool only ran _note_edited and
_reset_patch_failures, so the task's own patch changed the version and
left the baseline it held stale. _stale_overwrite_blocker then treated the
task like an external writer.
Invariant: after a task's own successful patch, the task may replace the
file whole exactly when it held a current full baseline for the bytes the
patch read and the bytes the patch wrote are what is on disk.
Lineage. a8af57fcd2 added the guard. dddefaefae counted paged, extracted
and post-compaction reads. e636aedebf kept a baseline across narrower
rereads of unchanged bytes and bound it to the sha256. That is the change
that made this sequence refuse (its parent lets the write through). Own
patches are the missing case of e636aedebf's principle that unchanged
knowledge survives.
Shape:
- Under the per-path locks, before the patch reads, patch_tool records
the sha256 of each path whose baseline still matches disk
(_known_full_content_sha256).
- read_file_raw and patch_replace report the sha256 of the exact bytes
they read, BOM included. Each file write records (path, read sha256,
written sha256) in PatchResult._writes for replace, V4A Update and V4A
Add.
- _carry_full_write_baselines marks the baseline only when the read
sha256 equals the known one (or the patch created the file). The mark
goes through _mark_full_write_baseline with the written sha256 as
expected_sha256. A writer that lands before the patch reads leaves a read
sha256 the task never knew. One that lands after the patch writes fails
the expected-sha check. Neither case gets a baseline. Several operations
on one file in one V4A patch chain in order.
- A blind patch (no baseline, or a partial view) is noted per task in
blind_patches. While disk still holds exactly those bytes, the refusal
says "Your patch changed this file after a partial view. Read the
current file in full before a whole-file overwrite, or continue with
targeted patches." Sibling, external and never-read refusals keep their
wording.
Remote backends: the baseline logic already stats the host path. On a
sandbox backend (non-LocalEnvironment env, verified with the
remote-binary-guard transport double), read_file records no baseline,
and _stale_overwrite_blocker lets the write through because the host path
does not exist. The carry hashes the same host path, so it records
nothing there. Paths the backend rewrites (translated mounts) do not match
the resolved host path and are skipped. Behaviour on those backends is
byte-identical to before.
Hint contradiction: after three failed replace patches, option (3) said
"use write_file to replace the entire file", which is the call the guard
refuses after a patch. It now says "re-read the file in full, then use
write_file to replace it".
Out of scope: enforcing recovery from a stale_write_blocked refusal
before a turn ends. The stale_write_blocked receipt and the file-mutation
footer are unchanged.
2026-10-06 14:28:01 +00:00
|
|
|
def _written(result: Any, diff: str, path: str, read_sha256: Optional[str]) -> ApplyResult:
|
|
|
|
|
"""Outcome of a write: its error, else success with LSP/lint propagated from the WriteResult
|
|
|
|
|
and the ``(path, read_sha256, written_sha256)`` record of the bytes it replaced and wrote."""
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if result.error:
|
|
|
|
|
return _fail(result.error)
|
fix(tools): a task's own patch keeps its full-file write baseline
A deployment reported that write_file -> read_file (full) -> patch ->
write_file refuses the last write with stale_write_blocked and "exists
but this task has not seen its full current content", in 50 of 50 trials.
No other writer took part. When the model does not reread before the turn
ends, the refusal surfaces as the "File-mutation verifier: N file edit(s)
FAILED" footer.
Mechanism. The write_file baseline is an exact file version: (st_dev,
st_ino, st_size, st_mtime_ns, st_ctime_ns, sha256)
(tools/file_tools_read_tracking.py _file_version, _mark_full_write_baseline,
_has_full_write_baseline). write_file_tool marks a fresh baseline from the
bytes it wrote. patch_tool only ran _note_edited and
_reset_patch_failures, so the task's own patch changed the version and
left the baseline it held stale. _stale_overwrite_blocker then treated the
task like an external writer.
Invariant: after a task's own successful patch, the task may replace the
file whole exactly when it held a current full baseline for the bytes the
patch read and the bytes the patch wrote are what is on disk.
Lineage. a8af57fcd2 added the guard. dddefaefae counted paged, extracted
and post-compaction reads. e636aedebf kept a baseline across narrower
rereads of unchanged bytes and bound it to the sha256. That is the change
that made this sequence refuse (its parent lets the write through). Own
patches are the missing case of e636aedebf's principle that unchanged
knowledge survives.
Shape:
- Under the per-path locks, before the patch reads, patch_tool records
the sha256 of each path whose baseline still matches disk
(_known_full_content_sha256).
- read_file_raw and patch_replace report the sha256 of the exact bytes
they read, BOM included. Each file write records (path, read sha256,
written sha256) in PatchResult._writes for replace, V4A Update and V4A
Add.
- _carry_full_write_baselines marks the baseline only when the read
sha256 equals the known one (or the patch created the file). The mark
goes through _mark_full_write_baseline with the written sha256 as
expected_sha256. A writer that lands before the patch reads leaves a read
sha256 the task never knew. One that lands after the patch writes fails
the expected-sha check. Neither case gets a baseline. Several operations
on one file in one V4A patch chain in order.
- A blind patch (no baseline, or a partial view) is noted per task in
blind_patches. While disk still holds exactly those bytes, the refusal
says "Your patch changed this file after a partial view. Read the
current file in full before a whole-file overwrite, or continue with
targeted patches." Sibling, external and never-read refusals keep their
wording.
Remote backends: the baseline logic already stats the host path. On a
sandbox backend (non-LocalEnvironment env, verified with the
remote-binary-guard transport double), read_file records no baseline,
and _stale_overwrite_blocker lets the write through because the host path
does not exist. The carry hashes the same host path, so it records
nothing there. Paths the backend rewrites (translated mounts) do not match
the resolved host path and are skipped. Behaviour on those backends is
byte-identical to before.
Hint contradiction: after three failed replace patches, option (3) said
"use write_file to replace the entire file", which is the call the guard
refuses after a patch. It now says "re-read the file in full, then use
write_file to replace it".
Out of scope: enforcing recovery from a stale_write_blocked refusal
before a turn ends. The stale_write_blocked receipt and the file-mutation
footer are unchanged.
2026-10-06 14:28:01 +00:00
|
|
|
write = (path, read_sha256, getattr(result, "_content_sha256", None))
|
2026-10-12 13:29:24 -04:00
|
|
|
return ApplyResult(True, diff, getattr(result, "lsp_diagnostics", None), getattr(result, "lint", None), write)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _unified_diff(path: str, old: str, new: Optional[str]) -> str:
|
|
|
|
|
"""Unified diff ``a/path`` -> ``b/path`` (``new=None`` = deletion, ``/dev/null``)."""
|
|
|
|
|
return ''.join(difflib.unified_diff(
|
|
|
|
|
old.splitlines(keepends=True), [] if new is None else new.splitlines(keepends=True),
|
|
|
|
|
fromfile=f"a/{path}", tofile="/dev/null" if new is None else f"b/{path}"))
|
|
|
|
|
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> PatchResult:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
"""Two-phase: validate everything, then apply (atomic on validation failure). A phase-2
|
|
|
|
|
failure (validate/apply race) carries a ``git diff`` note since state may be inconsistent.
|
|
|
|
|
``file_ops`` needs read_file_raw/write_file/delete_file/move_file."""
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _bullets(errs: list[str]) -> str:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return "\n".join(f" • {e}" for e in errs)
|
|
|
|
|
|
|
|
|
|
if errors := _validate_operations(operations, file_ops):
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
return PatchResult(
|
|
|
|
|
success=False,
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
error="Patch validation failed (no files were modified):\n" + _bullets(errors))
|
2026-10-08 17:22:54 +02:00
|
|
|
files: dict[str, list[str]] = {"created": [], "deleted": [], "modified": []}
|
|
|
|
|
all_diffs: list[str] = []
|
2026-10-12 13:29:24 -04:00
|
|
|
notes: list[str] = []
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
# V4A bypasses write_file's WriteResult plumbing: LSP diagnostics and lint propagate per file.
|
2026-10-08 17:22:54 +02:00
|
|
|
lsp_blocks: list[str] = []
|
|
|
|
|
lint_results: dict[str, dict] = {}
|
|
|
|
|
writes: list[tuple] = []
|
2026-02-05 03:49:46 -08:00
|
|
|
for op in operations:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
handler, verb, bucket = _APPLY_DISPATCH[op.operation]
|
2026-02-05 03:49:46 -08:00
|
|
|
try:
|
2026-10-12 13:29:24 -04:00
|
|
|
ok, payload, lsp, lint, write, op_notes = handler(op, file_ops)
|
2026-02-05 03:49:46 -08:00
|
|
|
except Exception as e:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
ok, payload = None, str(e)
|
|
|
|
|
if not ok:
|
|
|
|
|
prefix = f"Failed to {verb}" if ok is False else "Error processing"
|
|
|
|
|
errors.append(f"{prefix} {op.file_path}: {payload}")
|
|
|
|
|
continue
|
|
|
|
|
is_move = op.operation is OperationType.MOVE
|
|
|
|
|
files[bucket].append(f"{op.file_path} -> {op.new_path}" if is_move else op.file_path)
|
|
|
|
|
all_diffs.append(payload)
|
fix(tools): a task's own patch keeps its full-file write baseline
A deployment reported that write_file -> read_file (full) -> patch ->
write_file refuses the last write with stale_write_blocked and "exists
but this task has not seen its full current content", in 50 of 50 trials.
No other writer took part. When the model does not reread before the turn
ends, the refusal surfaces as the "File-mutation verifier: N file edit(s)
FAILED" footer.
Mechanism. The write_file baseline is an exact file version: (st_dev,
st_ino, st_size, st_mtime_ns, st_ctime_ns, sha256)
(tools/file_tools_read_tracking.py _file_version, _mark_full_write_baseline,
_has_full_write_baseline). write_file_tool marks a fresh baseline from the
bytes it wrote. patch_tool only ran _note_edited and
_reset_patch_failures, so the task's own patch changed the version and
left the baseline it held stale. _stale_overwrite_blocker then treated the
task like an external writer.
Invariant: after a task's own successful patch, the task may replace the
file whole exactly when it held a current full baseline for the bytes the
patch read and the bytes the patch wrote are what is on disk.
Lineage. a8af57fcd2 added the guard. dddefaefae counted paged, extracted
and post-compaction reads. e636aedebf kept a baseline across narrower
rereads of unchanged bytes and bound it to the sha256. That is the change
that made this sequence refuse (its parent lets the write through). Own
patches are the missing case of e636aedebf's principle that unchanged
knowledge survives.
Shape:
- Under the per-path locks, before the patch reads, patch_tool records
the sha256 of each path whose baseline still matches disk
(_known_full_content_sha256).
- read_file_raw and patch_replace report the sha256 of the exact bytes
they read, BOM included. Each file write records (path, read sha256,
written sha256) in PatchResult._writes for replace, V4A Update and V4A
Add.
- _carry_full_write_baselines marks the baseline only when the read
sha256 equals the known one (or the patch created the file). The mark
goes through _mark_full_write_baseline with the written sha256 as
expected_sha256. A writer that lands before the patch reads leaves a read
sha256 the task never knew. One that lands after the patch writes fails
the expected-sha check. Neither case gets a baseline. Several operations
on one file in one V4A patch chain in order.
- A blind patch (no baseline, or a partial view) is noted per task in
blind_patches. While disk still holds exactly those bytes, the refusal
says "Your patch changed this file after a partial view. Read the
current file in full before a whole-file overwrite, or continue with
targeted patches." Sibling, external and never-read refusals keep their
wording.
Remote backends: the baseline logic already stats the host path. On a
sandbox backend (non-LocalEnvironment env, verified with the
remote-binary-guard transport double), read_file records no baseline,
and _stale_overwrite_blocker lets the write through because the host path
does not exist. The carry hashes the same host path, so it records
nothing there. Paths the backend rewrites (translated mounts) do not match
the resolved host path and are skipped. Behaviour on those backends is
byte-identical to before.
Hint contradiction: after three failed replace patches, option (3) said
"use write_file to replace the entire file", which is the call the guard
refuses after a patch. It now says "re-read the file in full, then use
write_file to replace it".
Out of scope: enforcing recovery from a stale_write_blocked refusal
before a turn ends. The stale_write_blocked receipt and the file-mutation
footer are unchanged.
2026-10-06 14:28:01 +00:00
|
|
|
if write:
|
|
|
|
|
writes.append(write)
|
2026-10-12 13:29:24 -04:00
|
|
|
notes.extend(op_notes)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if lsp:
|
|
|
|
|
lsp_blocks.append(lsp)
|
|
|
|
|
if lint:
|
|
|
|
|
lint_results[op.file_path] = lint
|
|
|
|
|
# Each LSP block carries its own <diagnostics file="..."> header; joining keeps attribution.
|
|
|
|
|
return PatchResult(
|
|
|
|
|
success=not errors,
|
|
|
|
|
error=("Apply phase failed (state may be inconsistent — run `git diff` to assess):\n"
|
|
|
|
|
+ _bullets(errors)) if errors else None,
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
diff='\n'.join(all_diffs),
|
2026-09-02 22:52:52 -07:00
|
|
|
files_modified=files["modified"], files_created=files["created"], files_deleted=files["deleted"],
|
2026-10-05 16:42:06 +02:00
|
|
|
lint=lint_results or None, lsp_diagnostics="\n\n".join(lsp_blocks) or None, _writes=writes,
|
2026-10-12 13:29:24 -04:00
|
|
|
note="\n".join(dict.fromkeys(notes)) or None)
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
|
2026-08-03 16:47:54 +05:30
|
|
|
def _write_file_accepts_pre_content(file_ops: Any) -> bool:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
"""Whether ``file_ops.write_file`` accepts ``pre_content`` — read from the signature, not by
|
|
|
|
|
catching TypeError around the call, so a TypeError raised *inside* it can't double-write."""
|
2026-09-03 09:56:39 -07:00
|
|
|
try:
|
2026-08-03 16:47:54 +05:30
|
|
|
params = inspect.signature(file_ops.write_file).parameters
|
2026-09-03 09:56:39 -07:00
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
return False
|
|
|
|
|
return "pre_content" in params or any(
|
|
|
|
|
p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
|
2026-08-03 16:47:54 +05:30
|
|
|
|
|
|
|
|
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
def _apply_add(op: PatchOperation, file_ops: Any) -> ApplyResult:
|
fix(tools): reject V4A Add File onto an existing path
A V4A `*** Add File:` operation is meant to create a new file. The apply
path called `write_file` unconditionally and `_validate_operations` had no
pre-check for ADD, so an Add targeting a path that already existed
overwrote the file with only the patch's `+` lines, returned success, and
emitted a `--- /dev/null` diff that hid what was lost. Models frequently
confuse Add with Update, so this destroyed existing file contents with no
error. The MOVE path already guards its destination against clobbering;
ADD now follows the same rule.
Makes a V4A `Add File` operation fail when its target already exists,
instead of silently overwriting the existing file. Validation now rejects
the operation before any write happens, so the two-phase
validate-then-apply contract ("no files were modified" on a validation
failure) holds for ADD as it already does for UPDATE/MOVE/DELETE. A
matching re-check in the apply phase closes the validate-to-apply race.
N/A
- [x] 🐛 Bug fix (non-breaking change that fixes an issue)
- `tools/patch_parser.py`: add an ADD branch in `_validate_operations`
that errors when `read_file_raw` finds an existing file, and a
defensive existence re-check in `_apply_add` before `write_file`,
mirroring the existing MOVE destination guard.
- `tests/tools/test_patch_parser.py`: add a test asserting an Add onto an
existing path fails validation and leaves the original bytes unwritten;
add `read_file_raw` to three ADD-path LSP fakes so they match the real
`file_ops` interface now exercised on ADD.
1. Build a V4A patch with `*** Add File: <path>` where `<path>` already
exists on disk.
2. Apply it via `apply_v4a_operations`. Before this change the file is
overwritten with the patch's `+` lines and the result is success;
after, the result is a validation failure and the file is untouched.
3. Run `scripts/run_tests.sh tests/tools/test_patch_parser.py` —
`TestApplyOperations::test_add_onto_existing_file_fails_and_preserves_contents`
covers the regression.
- [x] I've read the [Contributing Guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md)
- [x] My commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`fix(scope):`, `feat(scope):`, etc.)
- [x] I searched for [existing PRs](https://github.com/NousResearch/hermes-agent/pulls) to make sure this isn't a duplicate
- [x] My PR contains **only** changes related to this fix/feature (no unrelated commits)
- [x] I've run `pytest tests/ -q` and all tests pass
- [x] I've added tests for my changes (required for bug fixes, strongly encouraged for features)
- [x] I've tested on my platform: macOS 15 (Darwin 25.5.0)
- [x] I've updated relevant documentation (README, `docs/`, docstrings) — or N/A
- [x] I've updated `cli-config.yaml.example` if I added/changed config keys — or N/A
- [x] I've updated `CONTRIBUTING.md` or `AGENTS.md` if I changed architecture or workflows — or N/A
- [x] I've considered cross-platform impact (Windows, macOS) per the [compatibility guide](https://github.com/NousResearch/hermes-agent/blob/main/CONTRIBUTING.md#cross-platform-compatibility) — or N/A
- [x] I've updated tool descriptions/schemas if I changed tool behavior — or N/A
2026-06-07 19:22:02 +03:00
|
|
|
"""Create a file from the hunks' '+' lines. Fails closed when the target already
|
|
|
|
|
exists: validation confirmed the path was free (or freed by an earlier DELETE in
|
|
|
|
|
this patch, which has already applied by now), so an existing file here is a
|
|
|
|
|
validate/apply race — never clobber."""
|
|
|
|
|
read_back = file_ops.read_file_raw(op.file_path)
|
|
|
|
|
if not read_back.error:
|
|
|
|
|
return _fail(f"{op.file_path}: file already exists — use Update File, not Add File")
|
fix(file-ops): a failed byte-exact read is not an absent file
Three defects in the byte-exact read this PR introduced.
base64 is not on every backend (busybox, distroless). The sample path
already degrades when it is missing; this one returned the read as a
failure, and read_file_raw is also _apply_add's existence check, which
treated any error as "the path is free". A backend with cat but no base64
turned `*** Add File` over an existing file into a silent overwrite that
reported success:
main: refused, "file already exists — use Update File"
PR head: b'KEEP ME -- months of work\n' -> b'clobbered by Add'
So: fall back to od (POSIX, in busybox) when base64 exits 127, and when
neither exists report a transport error. ReadResult grows not_found, set
only where the path is genuinely absent, and _apply_add refuses unless it
sees that flag — a read that FAILED can no longer pass as an absent path.
getattr keeps a producer without the field failing closed rather than
raising. The doubles in test_patch_parser that meant "absent" now say so.
The native fast path stat'd the path and then opened it, two lookups on a
name. A swap to a FIFO in between blocks the thread, and nothing times out
that. One O_RDONLY|O_NONBLOCK open, fstat on THAT descriptor, then read, so
a non-regular file is handed to the shell path and its timeout instead.
Tests: the od fallback round-trips byte-exactly and patches; an Add over a
file the backend cannot read is refused with the file intact; the native
read hands a FIFO to the shell rather than opening it. The first two go red
if their fix is removed. The third pins the property, not the race — with
one descriptor there is no window left to swap into, so reverting to
stat-then-open does not flip it.
Not addressed here: inserted text is still encoded UTF-8 regardless of the
file's declared encoding, so an edit adding non-ASCII to a latin-1 file
writes mixed bytes. That is the write half, it predates this PR, and it
needs source-encoding detection.
2026-09-24 09:40:44 +09:00
|
|
|
if not getattr(read_back, "not_found", False):
|
|
|
|
|
# The read FAILED; it did not report an absent path. Treating that as "the path is free"
|
|
|
|
|
# writes the Add payload over whatever is actually there.
|
|
|
|
|
return _fail(f"{op.file_path}: could not confirm the path is free — {read_back.error}")
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
content_lines = [line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+']
|
|
|
|
|
result = file_ops.write_file(op.file_path, '\n'.join(content_lines))
|
|
|
|
|
diff = f"--- /dev/null\n+++ b/{op.file_path}\n" + '\n'.join(f"+{line}" for line in content_lines)
|
fix(tools): a task's own patch keeps its full-file write baseline
A deployment reported that write_file -> read_file (full) -> patch ->
write_file refuses the last write with stale_write_blocked and "exists
but this task has not seen its full current content", in 50 of 50 trials.
No other writer took part. When the model does not reread before the turn
ends, the refusal surfaces as the "File-mutation verifier: N file edit(s)
FAILED" footer.
Mechanism. The write_file baseline is an exact file version: (st_dev,
st_ino, st_size, st_mtime_ns, st_ctime_ns, sha256)
(tools/file_tools_read_tracking.py _file_version, _mark_full_write_baseline,
_has_full_write_baseline). write_file_tool marks a fresh baseline from the
bytes it wrote. patch_tool only ran _note_edited and
_reset_patch_failures, so the task's own patch changed the version and
left the baseline it held stale. _stale_overwrite_blocker then treated the
task like an external writer.
Invariant: after a task's own successful patch, the task may replace the
file whole exactly when it held a current full baseline for the bytes the
patch read and the bytes the patch wrote are what is on disk.
Lineage. a8af57fcd2 added the guard. dddefaefae counted paged, extracted
and post-compaction reads. e636aedebf kept a baseline across narrower
rereads of unchanged bytes and bound it to the sha256. That is the change
that made this sequence refuse (its parent lets the write through). Own
patches are the missing case of e636aedebf's principle that unchanged
knowledge survives.
Shape:
- Under the per-path locks, before the patch reads, patch_tool records
the sha256 of each path whose baseline still matches disk
(_known_full_content_sha256).
- read_file_raw and patch_replace report the sha256 of the exact bytes
they read, BOM included. Each file write records (path, read sha256,
written sha256) in PatchResult._writes for replace, V4A Update and V4A
Add.
- _carry_full_write_baselines marks the baseline only when the read
sha256 equals the known one (or the patch created the file). The mark
goes through _mark_full_write_baseline with the written sha256 as
expected_sha256. A writer that lands before the patch reads leaves a read
sha256 the task never knew. One that lands after the patch writes fails
the expected-sha check. Neither case gets a baseline. Several operations
on one file in one V4A patch chain in order.
- A blind patch (no baseline, or a partial view) is noted per task in
blind_patches. While disk still holds exactly those bytes, the refusal
says "Your patch changed this file after a partial view. Read the
current file in full before a whole-file overwrite, or continue with
targeted patches." Sibling, external and never-read refusals keep their
wording.
Remote backends: the baseline logic already stats the host path. On a
sandbox backend (non-LocalEnvironment env, verified with the
remote-binary-guard transport double), read_file records no baseline,
and _stale_overwrite_blocker lets the write through because the host path
does not exist. The carry hashes the same host path, so it records
nothing there. Paths the backend rewrites (translated mounts) do not match
the resolved host path and are skipped. Behaviour on those backends is
byte-identical to before.
Hint contradiction: after three failed replace patches, option (3) said
"use write_file to replace the entire file", which is the call the guard
refuses after a patch. It now says "re-read the file in full, then use
write_file to replace it".
Out of scope: enforcing recovery from a stale_write_blocked refusal
before a turn ends. The stale_write_blocked receipt and the file-mutation
footer are unchanged.
2026-10-06 14:28:01 +00:00
|
|
|
return _written(result, diff, op.file_path, "")
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
def _apply_delete(op: PatchOperation, file_ops: Any) -> ApplyResult:
|
|
|
|
|
"""Delete a file, producing a real unified diff of the removed content."""
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
read_result = file_ops.read_file_raw(op.file_path) # re-read guards validate/apply races
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
if read_result.error:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return _fail(f"Cannot delete {op.file_path}: file not found")
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
result = file_ops.delete_file(op.file_path)
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
diff = _unified_diff(op.file_path, read_result.content, None) or f"# Deleted: {op.file_path}"
|
2026-10-12 13:29:24 -04:00
|
|
|
return _fail(result.error) if result.error else ApplyResult(True, diff)
|
2026-02-05 03:49:46 -08:00
|
|
|
|
|
|
|
|
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
def _apply_move(op: PatchOperation, file_ops: Any) -> ApplyResult:
|
2026-09-24 18:28:47 +09:00
|
|
|
"""Move, re-checking the destination first: validation's answer is stale once earlier ops of
|
|
|
|
|
this patch have applied, and ``mv`` replaces whatever is there."""
|
|
|
|
|
dst = file_ops.read_file_raw(op.new_path)
|
|
|
|
|
if not dst.error:
|
|
|
|
|
return _fail(f"{op.new_path}: destination already exists — move would overwrite")
|
|
|
|
|
if not getattr(dst, "not_found", False):
|
|
|
|
|
return _fail(f"{op.new_path}: could not confirm the destination is free — {dst.error}")
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
result = file_ops.move_file(op.file_path, op.new_path)
|
2026-10-12 13:29:24 -04:00
|
|
|
return _fail(result.error) if result.error else ApplyResult(
|
|
|
|
|
True, f"# Moved: {op.file_path} -> {op.new_path}")
|
fix(patch): harden V4A patch parser and fuzzy match — 9 correctness bugs
- Bug 1: replace read_file(limit=10000) with read_file_raw in _apply_update,
preventing silent truncation of files >2000 lines and corruption of lines
>2000 chars; add read_file_raw to FileOperations abstract interface and
ShellFileOperations
- Bug 2: split apply_v4a_operations into validate-then-apply phases; if any
hunk fails validation, zero writes occur (was: continue after failure,
leaving filesystem partially modified)
- Bug 3: parse_v4a_patch now returns an error for begin-marker-with-no-ops,
empty file paths, and moves missing a destination (was: always returned
error=None)
- Bug 4: raise strategy 7 (block anchor) single-candidate similarity threshold
from 0.10 to 0.50, eliminating false-positive matches in repetitive code
- Bug 5: add _strategy_unicode_normalized (new strategy 7) with position
mapping via _build_orig_to_norm_map; smart quotes and em-dashes in
LLM-generated patches now match via strategies 1-6 before falling through
to fuzzy strategies
- Bug 6: extend fuzzy_find_and_replace to return 4-tuple (content, count,
error, strategy); update all 5 call sites across patch_parser.py,
file_operations.py, and skill_manager_tool.py
- Bug 7: guard in _apply_update returns error when addition-only context hint
is ambiguous (>1 occurrences); validation phase errors on both 0 and >1
- Bug 8: _apply_delete returns error (not silent success) on missing file
- Bug 9: _validate_operations checks source existence and destination absence
for MOVE operations before any write occurs
2026-04-10 00:11:07 +02:00
|
|
|
|
2026-02-05 03:49:46 -08:00
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _insert_addition_only(new_content: str, hunk: Hunk, insert_text: str) -> tuple[Optional[str], Optional[str]]:
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
"""Place an addition-only hunk after its context hint (or at EOF). Returns (content, error)."""
|
|
|
|
|
if hunk.context_hint:
|
2026-09-02 22:42:07 -07:00
|
|
|
occurrences, ambiguous = _hint_ambiguity(
|
|
|
|
|
new_content, hunk.context_hint, " — provide a more unique hint")
|
2026-09-02 22:26:02 -07:00
|
|
|
if ambiguous:
|
|
|
|
|
return None, f"Addition-only hunk: {ambiguous}"
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if occurrences == 1:
|
2026-09-02 22:26:02 -07:00
|
|
|
eol = new_content.find('\n', new_content.find(hunk.context_hint))
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
if eol == -1:
|
|
|
|
|
return new_content + '\n' + insert_text, None
|
|
|
|
|
return new_content[:eol + 1] + insert_text + '\n' + new_content[eol + 1:], None
|
|
|
|
|
# No hint / hint not found — append at end as a safe fallback.
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
return new_content.rstrip('\n') + '\n' + insert_text + '\n', None
|
2026-02-05 03:49:46 -08:00
|
|
|
|
fix(lint): skip per-file shell linter when LSP will handle the file (#29054)
* fix(lint): skip per-file shell linter when LSP will handle the file
`_check_lint` ran `npx tsc --noEmit FILE.ts` after every `.ts`/`.tsx`
edit. `tsc` ignores `tsconfig.json` when given an explicit file argument
(documented quirk) and defaults to no-lib / ES5, so every ES2015+ stdlib
reference reports as missing:
- `Cannot find global value 'Promise'`
- `Cannot find name 'Map' / 'Set' / 'ReadonlySet' / 'Iterable'`
- `Property 'isFinite' does not exist on type 'NumberConstructor'`
- `Module 'phaser' can only be default-imported using esModuleInterop`
- `import.meta is only allowed when --module is es2020+`
On real TypeScript projects this floods the `lint` field on
WriteResult / PatchResult with up to 25K tokens of false positives
per edit. The delta filter in `_check_lint_delta` is supposed to mask
them, but a tiny edit shifts line numbers and every phantom resurfaces
as "introduced by this edit". The result is a 1MB+ phantom-error dump
on every patch that eats the agent's context budget. Same shape for
`.go` (`go vet` outside a module) and `.rs` (`rustfmt --check` outside
a Cargo project).
PR #24168 added an LSP tier on top of this — real `tsserver` / `gopls`
/ `rust-analyzer` diagnostics surface in the separate `lsp_diagnostics`
field. But the broken shell linter kept running underneath, so the
phantom-error dump kept happening even when LSP was giving us a clean
authoritative signal.
This change short-circuits the shell linter for the structurally-broken
extensions (`.ts`, `.tsx`, `.go`, `.rs`) when an LSP server is active
and claims the file via `LSPService.enabled_for(path)`. The LSP tier
runs as before and carries the real diagnostics in `lsp_diagnostics`.
Other shell linters (`py_compile`, `node --check`) keep running
unconditionally — they're fast, file-local, and correct.
Default behavior (LSP disabled, LSP misconfigured, remote backend, file
outside a workspace) is unchanged — the existing fallback paths trigger
when `_lsp_will_handle` returns False, so users who haven't opted into
LSP get the same shell-linter behavior they had before.
Drive-by: `.tsx` was missing from the `LINTERS` table entirely, so TS
React files got no post-edit syntax check at all. Added it for
symmetry; in practice it now hits the LSP-skip path.
Tests:
- `tests/agent/lsp/test_shell_linter_lsp_skip.py` — 14 tests covering:
* skip happens for each redundant extension when LSP claims the file
(asserted by patching `_exec` to raise on any shell-linter call)
* shell linter still runs when LSP is inactive (regression guard)
* `.py` / `.js` continue to run unconditionally even with LSP active
* `_lsp_will_handle` is exception-safe: returns False on None
service, remote backend, or `enabled_for` raising
* `.tsx` is in both `LINTERS` and `_SHELL_LINTER_LSP_REDUNDANT`
- All pre-existing tests in `tests/agent/lsp/` and
`tests/tools/test_file_operations*.py` still pass (233/233).
* fix(lint): address Copilot review on #29054
Two fixes from copilot-pull-request-reviewer on PR #29054:
1. `.tsx` regression with LSP disabled
(https://github.com/NousResearch/hermes-agent/pull/29054#discussion_r3271017282)
The first revision added `.tsx` to the `LINTERS` table so that
TypeScript React files would hit the LSP skip path. Side effect:
when LSP is *disabled* (the default), `.tsx` edits would suddenly
run `npx tsc --noEmit FILE.tsx` and inherit the same phantom-error
dump this PR is supposed to fix. Pre-PR behavior was implicit
`skipped` (no `LINTERS` entry); restore that.
- Remove `.tsx` from `LINTERS`.
- Remove `.tsx` from `_SHELL_LINTER_LSP_REDUNDANT` (the skip path
is unreachable without a `LINTERS` entry — falls through to
`ext not in LINTERS` first).
- When LSP IS enabled, `.tsx` is still covered by the LSP tier
via `_maybe_lsp_diagnostics` (typescript-language-server's
`extensions` tuple includes `.tsx`), so the diagnostics still
surface — just on the `lsp_diagnostics` channel, not `lint`.
- Update test_shell_linter_lsp_skip.py to reflect this contract
(drop `.tsx` from the parametrize lists; add
`test_tsx_stays_out_of_linters_table_for_default_compatibility`
and `test_tsx_default_check_lint_returns_skipped`).
2. V4A patches dropped `WriteResult.lsp_diagnostics`
(https://github.com/NousResearch/hermes-agent/pull/29054#discussion_r3271017295)
`tools/patch_parser.py::apply_v4a_operations` calls
`file_ops.write_file()` per operation, then calls `_check_lint()`
directly afterwards — but never propagates `WriteResult.lsp_diagnostics`
to the `PatchResult`. The shell-linter skip introduced in this PR
makes the gap visible: a `.ts` / `.go` / `.rs` V4A patch with LSP
active would return `lint = {f: {skipped: True}}` and zero
diagnostics from any channel.
- `_apply_add` and `_apply_update` now return
`Tuple[bool, str, Optional[str]]` where the third element is
`WriteResult.lsp_diagnostics` (or `None` on failure / no diags).
- `_apply_delete` and `_apply_move` stay 2-tuples — they don't
produce diagnostics, no write goes through `write_file`.
- `apply_v4a_operations` accumulates per-file diagnostics blocks
and surfaces a combined block on `PatchResult.lsp_diagnostics`.
Each block already carries its `<diagnostics file="...">` header
from `LSPService.report_for_file`, so concatenation preserves
per-file attribution.
Tests added (`test_patch_parser.py::TestV4ALspDiagnosticsPropagation`):
- ADD op: `WriteResult.lsp_diagnostics` flows to `PatchResult`
- UPDATE op: same
- No diagnostics → `PatchResult.lsp_diagnostics is None` (not "")
- Multi-file patch: combined block contains every per-file block
Verification:
- Targeted test scope: 257/257 pass
(tests/agent/lsp/, tests/tools/test_file_operations*.py,
tests/tools/test_patch_parser.py)
- Wider sweep: 5400 pass; 11 failures all pre-existing on origin/main
(file_staleness / file_read_guards / file_state_registry — unrelated
macOS /var/folders tmp-path sensitivity issues, confirmed by
re-running on a clean origin/main checkout)
* docs(test): align shell-linter LSP skip docstring with .tsx behavior
Copilot review feedback (review #4324947616, comment #3271049036):
the test module docstring still listed .tsx alongside .ts/.go/.rs in
the skip contract, but .tsx is now intentionally NOT in LINTERS or
_SHELL_LINTER_LSP_REDUNDANT. Updated the bullet list to drop .tsx from
the skip contract and added a paragraph documenting why .tsx is left
out (preserves pre-PR implicit-skip behavior for LSP-disabled users;
LSP coverage still happens via _maybe_lsp_diagnostics).
* test(lsp): drop unused tmp_path from _make_fops helper
Copilot review #3271069484: the helper accepted tmp_path but never
used it. Callers still need tmp_path themselves for the file they're
asserting against, so we just drop the helper's parameter.
2026-05-20 01:46:40 -05:00
|
|
|
|
2026-10-12 13:29:24 -04:00
|
|
|
def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult:
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
"""Apply each hunk via fuzzy replace, then write once."""
|
2026-10-12 13:29:24 -04:00
|
|
|
from tools.fuzzy_match import boundary_note, fuzzy_find_and_replace, is_already_applied
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
read_result = file_ops.read_file_raw(op.file_path) # raw: no line numbers / truncation
|
2026-02-05 03:49:46 -08:00
|
|
|
if read_result.error:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return _fail(f"Cannot read file: {read_result.error}")
|
|
|
|
|
current_content = new_content = read_result.content
|
2026-10-12 13:29:24 -04:00
|
|
|
notes: list[str] = [] # escape-drift corrections, appended by fuzzy_find_and_replace
|
|
|
|
|
strategies: list[str] = [] # the fuzzy strategies that located the hunks
|
2026-02-05 03:49:46 -08:00
|
|
|
for hunk in op.hunks:
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
search_lines, replace_lines = _split_hunk(hunk)
|
2026-07-13 02:42:18 -07:00
|
|
|
if search_lines and search_lines == replace_lines:
|
|
|
|
|
continue
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
search_pattern, replacement = '\n'.join(search_lines), '\n'.join(replace_lines)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if not search_lines:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
new_content, err = _insert_addition_only(new_content, hunk, replacement)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if err:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
return _fail(err)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
continue
|
2026-10-05 11:21:00 +02:00
|
|
|
new_content, count, strategy, error = fuzzy_find_and_replace(
|
2026-10-12 13:29:24 -04:00
|
|
|
new_content, search_pattern, replacement, replace_all=False, correction_notes=notes)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if not (error and count == 0):
|
2026-10-05 11:21:00 +02:00
|
|
|
if count > 0:
|
2026-10-12 13:29:24 -04:00
|
|
|
strategies.append(strategy)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
continue
|
|
|
|
|
# Retry inside a window around the context hint, if any.
|
2026-09-02 22:26:02 -07:00
|
|
|
hint_pos = new_content.find(hunk.context_hint) if hunk.context_hint else -1
|
|
|
|
|
if hint_pos != -1:
|
|
|
|
|
window_start = max(0, hint_pos - 500)
|
|
|
|
|
window_end = min(len(new_content), hint_pos + 2000)
|
2026-10-05 11:21:00 +02:00
|
|
|
window_new, count, strategy, error = fuzzy_find_and_replace(
|
2026-10-05 16:42:06 +02:00
|
|
|
new_content[window_start:window_end], search_pattern, replacement, replace_all=False,
|
2026-10-12 13:29:24 -04:00
|
|
|
correction_notes=notes)
|
2026-09-02 22:26:02 -07:00
|
|
|
if count > 0:
|
2026-10-12 13:29:24 -04:00
|
|
|
strategies.append(strategy)
|
2026-09-02 22:26:02 -07:00
|
|
|
new_content = new_content[:window_start] + window_new + new_content[window_end:]
|
|
|
|
|
error = None
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if error:
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
# Mirror validation's already-applied skip, else the two phases disagree and fail here.
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
if is_already_applied(new_content, search_pattern, replacement):
|
|
|
|
|
continue
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
hint = _no_match_hint(error, search_pattern, new_content)
|
|
|
|
|
return _fail(f"Could not apply hunk: {error}" + hint)
|
refactor(tools): first-wave simplification of tools/ (file ops split, lazy_deps, code_exec, approval, browser, delegate, mcp, skills, terminal, voice, media)
Behavior-neutral structural pass over tools/*: god-file extractions into
sibling modules (file_operations_common/lint/search, file_tools_paths/
read_tracking/write, code_execution_env/rpc, tool_search_catalog/names/
validation, tts_command_provider, ...), duplicate helper unification,
if/elif -> dispatch tables, dead-code removal, docstring compaction.
Tool schemas (get_tool_definitions) verified byte-identical to base.
2026-09-02 09:20:54 -07:00
|
|
|
# Pass pre_content to skip a redundant re-read inside write_file when supported.
|
refactor(tools): wave-2 group M — read_extract/patch_parser/shell_heredoc/self_repo_guard/schema_sanitizer -12% LOC (68% code)
- patch_parser: shared _fail/_written/_unified_diff apply helpers, single PatchResult build,
flattened apply loop, merged inert/no-op hunk skips, overlay _remove, dropped never-set
PatchOperation.content
- self_repo_guard: conditional git-mutation predicates as a dispatch table over one _has_flag,
unified git global-option/alias parse, suppress() for resolve/alias/shlex, folded scope and
heredoc scanners
- shell_heredoc: unit scanner and operator parser as single if/elif ladders, unified quote masking
- read_extract: groupby gap runs, single try for anydoc, islice/suppress xlsx loops, folded
notebook/docx render loops, _zip_xml optional -> empty element
- schema_sanitizer: folded rename/type-array/recovery-strip loops, _dict_nodes/_carry_union_meta
- docstrings/comments compacted by hand (every WHY kept)
Verified: tool-schema dump byte-identical (SCHEMA-OK); golden corpus over pure functions and
every registry schema + edge cases byte-identical vs 113f046 base (GOLDEN-OK); 95 test files
2517 passed (2 pre-existing reds in test_web_tools_config also fail on base).
2026-09-03 01:41:16 -07:00
|
|
|
extra = {"pre_content": current_content} if _write_file_accepts_pre_content(file_ops) else {}
|
|
|
|
|
write_result = file_ops.write_file(op.file_path, new_content, **extra)
|
2026-10-05 16:42:06 +02:00
|
|
|
result = _written(write_result, _unified_diff(op.file_path, current_content, new_content),
|
|
|
|
|
op.file_path, getattr(read_result, "_content_sha256", None))
|
2026-10-12 13:29:24 -04:00
|
|
|
if not result.ok:
|
|
|
|
|
return result
|
|
|
|
|
# A hunk found by a similarity strategy may have landed a line off; say so, per file.
|
|
|
|
|
if note := boundary_note(strategies, "the hunk's", f" in {op.file_path}"):
|
|
|
|
|
notes.append(note)
|
|
|
|
|
return result._replace(notes=tuple(notes))
|
2026-09-02 22:52:52 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# operation -> (handler, verb for error text, files_* bucket)
|
2026-10-08 17:22:54 +02:00
|
|
|
_APPLY_DISPATCH: dict[OperationType, tuple[Callable[[PatchOperation, Any], ApplyResult], str, str]] = {
|
2026-09-02 22:52:52 -07:00
|
|
|
OperationType.ADD: (_apply_add, "add", "created"),
|
|
|
|
|
OperationType.DELETE: (_apply_delete, "delete", "deleted"),
|
|
|
|
|
OperationType.MOVE: (_apply_move, "move", "modified"),
|
|
|
|
|
OperationType.UPDATE: (_apply_update, "update", "modified"),
|
|
|
|
|
}
|