From f70048f091de18a5ce35964fff5231070e9a66c6 Mon Sep 17 00:00:00 2001 From: KuljeetSinghXDA <22261392+KuljeetSinghXDA@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:13:25 +0530 Subject: [PATCH] fix(builtin): preserve leading blank lines in fs.edit when start > 0 --- src/bub/builtin/tools.py | 4 +++- tests/test_environment.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/bub/builtin/tools.py b/src/bub/builtin/tools.py index 80bf2e1e..f54f4bc2 100644 --- a/src/bub/builtin/tools.py +++ b/src/bub/builtin/tools.py @@ -358,6 +358,8 @@ async def fs_write(path: str, content: str, *, context: ToolContext) -> str: @tool(context=True, name="fs.edit", exposure="direct") async def fs_edit(path: str, old: str, new: str, start: int = 0, *, context: ToolContext) -> str: """Edit a text file by replacing old text with new text. You can specify the line number to start searching for the old text.""" + if start < 0: + raise ValueError("start must be non-negative") environment = environment_from_state(context.state) resolved_path = environment.resolve_path(path) text = await environment.read_text(resolved_path) @@ -366,7 +368,7 @@ async def fs_edit(path: str, old: str, new: str, start: int = 0, *, context: Too if old not in to_replace: raise ValueError(f"'{old}' not found in {resolved_path} from line {start}") replaced = to_replace.replace(old, new) - if prev: + if start > 0: replaced = prev + "\n" + replaced if text.endswith(("\n", "\r")): replaced += "\n" diff --git a/tests/test_environment.py b/tests/test_environment.py index ce6a8908..e2264d08 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -93,6 +93,27 @@ async def test_fs_edit_preserves_trailing_newline(tmp_path: Path) -> None: assert environment.files == {"/environment/work/a.py": "x = 1\ny = 3\n"} +@pytest.mark.asyncio +async def test_fs_edit_preserves_leading_blank_line_when_start_is_one(tmp_path: Path) -> None: + environment = MemoryEnvironment() + context = _context(tmp_path, environment) + + await builtin_tools.fs_write.run(path="a.py", content="\ny = 2\n", context=context) + await builtin_tools.fs_edit.run(path="a.py", old="y = 2", new="y = 3", start=1, context=context) + + assert environment.files == {"/environment/work/a.py": "\ny = 3\n"} + + +@pytest.mark.asyncio +async def test_fs_edit_rejects_negative_start(tmp_path: Path) -> None: + environment = MemoryEnvironment() + context = _context(tmp_path, environment) + + await builtin_tools.fs_write.run(path="a.py", content="x = 1\ny = 2\n", context=context) + with pytest.raises(ValueError, match="non-negative"): + await builtin_tools.fs_edit.run(path="a.py", old="y = 2", new="y = 3", start=-1, context=context) + + @pytest.mark.asyncio async def test_bash_spawns_in_the_session_environment_with_cwd_resolved_there(tmp_path: Path, monkeypatch) -> None: monkeypatch.setattr(builtin_tools, "shell_manager", ShellManager())