Skip to content

Conversation

@jaufgang
Copy link

@jaufgang jaufgang commented Dec 5, 2025

Summary

This PR implements a comprehensive set of file editing tools to address gaps identified in microsoft/vscode#281417. It adds three new tools that complement the existing editing tools by providing different editing paradigms:

  1. replace_file_contents - Whole-file replacement for complete rewrites
  2. insert_at_line - Line-based insertion without text matching
  3. delete_lines - Line-based deletion without text matching

Motivation

This PR stems from a conversation where Claude (running as the Copilot Chat backend) was asked: "What editing tools would help you do your job most efficiently?" The answer identified specific gaps in the current toolset that make certain common editing tasks unnecessarily difficult or fragile.

The goal is to empower the AI with a complete toolkit for file editing, covering the full spectrum from surgical single-line changes to complete file rewrites.

Problem Statement

The existing editing tools (replace_string_in_file, multi_replace_string_in_file) are optimized for surgical edits with exact string matching. This creates pain points for:

Scenario Current Pain Point
Complete file rewrites (e.g., SQL → Mermaid ERD) 50+ fragile replace_string_in_file calls
Adding imports to unknown file structure Must match existing content exactly
Removing deprecated code by position Must reproduce exact whitespace/content
Major refactoring touching every line High failure rate from format changes

Solution: Three Complementary Tools

1. replace_file_contents (Original Request)

Replace entire file contents in a single atomic operation.

replace_file_contents({
  filePath: "/path/to/file.ts",
  newContent: "// Complete new content...",
  explanation: "Convert to new format"
})

Use cases: Format conversions, major refactoring, complete restructuring

2. insert_at_line (Follow-up Request)

Insert content at a specific line number without matching existing text.

insert_at_line({
  filePath: "/path/to/file.ts",
  line: 1,
  content: "import { newDep } from 'lib';",
  position: "before"  // or "after"
})

Use cases: Adding imports, inserting methods, adding list entries

3. delete_lines (Follow-up Request)

Delete lines by position without reproducing exact content.

delete_lines({
  filePath: "/path/to/file.ts",
  startLine: 45,
  endLine: 50
})

Use cases: Removing deprecated code, cleaning up comments, deleting generated sections

Why These Tools Matter

Robustness to Formatting Changes

Line numbers are stable references; exact string content is not. IDE formatters, auto-save, and linters constantly modify whitespace, causing string-match failures.

Simpler Mental Model

"Insert at line 15" and "delete lines 45-50" map directly to how developers think about code changes.

Reduced Token Usage

Current approach requires sending content to match/delete. Line-based operations just need numbers.

Better Error Messages

"Line 45 doesn't exist" is clearer than "Could not find exact match for 47-character string..."

Tool Coverage Matrix

Task Recommended Tool
Change one function signature replace_string_in_file
Update 3 related code blocks multi_replace_string_in_file
Fix a typo replace_string_in_file
Restructure entire file replace_file_contents
Convert doc format replace_file_contents
Add imports at top insert_at_line
Insert new method insert_at_line
Remove deprecated code delete_lines
Clean up line range delete_lines

Implementation Details

All three tools:

  • ✅ Integrate with VS Code's undo stack (Ctrl+Z works)
  • ✅ Use WorkspaceEdit API for proper change tracking
  • ✅ Show diff preview via createEditConfirmation
  • ✅ Trigger proper file change events for extensions
  • ✅ Include telemetry tracking
  • ✅ Support existing file validation

Testing

Unit tests added for all tools covering:

  • Core functionality (insertion, deletion, replacement)
  • Edge cases (beginning/end of file, empty files)
  • Error handling (non-existent files, invalid line numbers)
  • Result format verification

Files Changed

File Purpose
src/extension/tools/node/replaceFileContentsTool.tsx replace_file_contents implementation
src/extension/tools/node/insertAtLineTool.tsx insert_at_line implementation
src/extension/tools/node/deleteLinesTool.tsx delete_lines implementation
src/extension/tools/node/test/*.spec.tsx Unit tests
src/extension/tools/common/toolNames.ts Tool name enums + categories
src/extension/tools/node/allTools.ts Tool registration
package.json Tool schema definitions
package.nls.json Localization strings

Out of Scope: Enabling apply_patch for Claude

The original issue thread includes a follow-up comment suggesting enabling the existing apply_patch tool for Claude models. This was intentionally not included in this PR because:

  1. Different type of change: The tools in this PR are additive (new capabilities). Enabling apply_patch for Claude is a behavioral change affecting all existing Claude users.

  2. Requires experimentation: Changing which edit tool a model uses by default should likely be A/B tested to ensure Claude produces correct patch syntax reliably.

  3. Scope clarity: This PR focuses on providing new tools that any model can use. Model-specific capability flags are a separate concern.

If there's interest in enabling apply_patch for Claude, that would be a good candidate for a separate PR with its own testing/rollout plan.

Splitting Consideration

This PR could be split into separate PRs for each tool if preferred:

  1. PR for replace_file_contents (original request)
  2. PR for insert_at_line (follow-up This repo is missing a LICENSE file #1)
  3. PR for delete_lines (follow-up Adding Microsoft SECURITY.MD #2)

Submitted as a single PR for unified initial review, but happy to split if that's preferred for easier review/merge.

Fixes microsoft/vscode#281417


🤖 Meta: AI Building Tools for Itself

This PR was created by GitHub Copilot (Claude Opus 4.5) after a human asked: "What tools would help you edit files most efficiently?" The original issue was also written by Claude—while running as the Copilot Chat backend—after experiencing the tooling limitations firsthand during a real user session.

Full loop: AI identifies gap → AI proposes solution → Human posts issue → Human asks AI to implement → AI builds the tools → Human pushes PR 🚀

Implements a new tool that replaces entire file contents in a single operation,
addressing the gap identified in microsoft/vscode#281417.

## Problem

The existing editing tools (replace_string_in_file, multi_replace_string_in_file)
are designed for surgical edits with exact string matching. For complete file
rewrites like format conversions or major refactoring, these tools require many
fragile sequential calls that can fail if the file is modified between calls.

## Solution

This PR adds a new `replace_file_contents` tool that:

- Accepts complete new file content as input
- Uses processFullRewrite to stream edits via VS Code's WorkspaceEdit API
- Integrates with VS Code's undo stack (Ctrl+Z works)
- Shows diff preview for sensitive files via createEditConfirmation
- Returns diagnostics via EditFileResult component

## When to use

- Complete file rewrites (e.g., SQL schema → Mermaid ERD)
- Major refactoring (e.g., class → functional React)
- Format/convention changes affecting most lines

For surgical edits, replace_string_in_file remains the better choice.

Fixes microsoft/vscode#281417
Adds unit tests covering:
- Full file content replacement
- Structural rewrites (function syntax conversion)
- Error handling for non-existent files
- Result format verification
Extends the tool to handle notebook files (.ipynb) using the same pattern
as createFileTool:
- Uses processFullRewriteNotebook for notebook documents
- Adds INotebookService, IAlternativeNotebookContentService dependencies
- Tracks isNotebook in telemetry
- Returns appropriate result format for notebooks vs text files
@jaufgang
Copy link
Author

jaufgang commented Dec 5, 2025

@microsoft-github-policy-service agree

jaufgang and others added 2 commits December 5, 2025 10:59
Implements two new line-based editing tools as requested in microsoft/vscode#281417 follow-up comments:

- insert_at_line: Insert content at a specific line number (before/after)
- delete_lines: Delete lines by line number range (inclusive)

These tools complement the existing editing tools by providing position-based
operations that don't require exact text matching, making them more robust
to formatting changes.
@jaufgang jaufgang changed the title feat: Add replace_file_contents tool for whole-file rewrites feat: Add file editing tools (replace_file_contents, insert_at_line, delete_lines) Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request From Claude: Add replace_file_contents tool for Copilot Chat agent mode

2 participants