Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(agent): file_edit buendelt mehrere Aenderungen in einem Aufruf und vertraegt Einrueckungsdrift

purplef97689126f9c
diff --git a/e2e/coding-agent.spec.ts b/e2e/coding-agent.spec.ts
index c008a8dc..a1b48a5d 100644
--- a/e2e/coding-agent.spec.ts
+++ b/e2e/coding-agent.spec.ts
@@ -306,3 +306,34 @@ test('the plan the model writes shows up above the composer and tracks progress'
const calls = await toolCalls(page)
expect(calls.filter((c) => c.cmd === 'todo_write')).toEqual([])
})
+
+test('file_edit: several edits in one call, one of them with the indentation off, land in one write', async ({ page }) => {
+ // 01.10.2026: every failed edit on a paid model was "read again, retry",
+ // two more full-context round trips. The model here sends two changes in one
+ // call, and copies the first with an indentation the file does not have.
+ await bootAgentMode(page, [
+ {
+ text: 'patching',
+ toolCalls: [{
+ name: 'file_edit',
+ args: {
+ path: 'big.ts',
+ edits: [
+ { old_string: ' line 10\n line 11', new_string: ' LINE TEN\n LINE ELEVEN' },
+ { old_string: 'line 150', new_string: 'LINE 150' },
+ ],
+ },
+ }],
+ },
+ { text: 'EDITS_DONE' },
+ ])
+
+ await instruct(page, 'rename line 10, 11 and 150 in big.ts')
+ await expect(page.getByRole('main').getByText('EDITS_DONE')).toBeVisible({ timeout: 30_000 })
+
+ const writes = (await toolCalls(page)).filter((c) => c.cmd === 'fs_write')
+ expect(writes).toHaveLength(1)
+ const content = String(writes[0].raw.content)
+ expect(content).toContain('line 9\nLINE TEN\nLINE ELEVEN\nline 12')
+ expect(content).toContain('line 149\nLINE 150\nline 151')
+})
diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.ts
index 54fd0792..382cac02 100644
--- a/e2e/support/tauri-mock.ts
+++ b/e2e/support/tauri-mock.ts
@@ -610,7 +610,7 @@ export function tauriMockInit(opts: TauriMockOptions) {
return Promise.resolve({ content: key ? files[key] : '', encoding: 'utf8' })
}
case 'fs_write':
- record('__E2E_TOOL_CALLS__', { cmd, path: m?.path })
+ record('__E2E_TOOL_CALLS__', { cmd, path: m?.path, content: m?.content })
return Promise.resolve({ ok: true, path: m?.path })
case 'fs_list':
record('__E2E_TOOL_CALLS__', { cmd, path: m?.path })
diff --git a/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts b/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts
index 7044958d..2433180c 100644
--- a/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts
+++ b/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts
@@ -68,7 +68,7 @@ const PFLICHT: Record<string, Record<string, string>> = {
web_fetch: { url: 'https://example.com/a' },
file_read: { path: 'a.ts' },
file_write: { path: 'a.ts', content: 'neu' },
- file_edit: { path: 'a.ts', old_string: 'alt', new_string: 'neu' },
+ file_edit: { path: 'a.ts' },
file_list: { path: '.' },
file_search: { path: '.', pattern: 'alt' },
pr_resume: { url: 'https://github.com/o/r/pull/1' },
@@ -187,6 +187,18 @@ describe('die Pruefung sperrt nicht aus, was gemeint sein kann', () => {
expect(call?.body.path).toBe('leer.txt')
})
+ // file_edit verlangt im Katalog nur `path`, weil `edits` die beiden Felder
+ // ersetzen kann. Ohne beides darf trotzdem nichts geschrieben werden.
+ it.each([
+ [{ path: 'a.ts', new_string: 'neu' }, 'old_string'],
+ [{ path: 'a.ts', old_string: 'alt' }, 'new_string'],
+ [{ path: 'a.ts', edits: [{ old_string: 'alt' }] }, 'new_string'],
+ ])('file_edit %j schreibt nichts und nennt %s', async (args, fehlt) => {
+ const out = await registry.execute('file_edit', args)
+ expect(out).toContain(fehlt)
+ expect(befehle()).not.toContain('fs_write')
+ })
+
it('new_string: "" loescht weiterhin Text', async () => {
await registry.execute('file_edit', { path: 'a.ts', old_string: 'alt', new_string: '' })
const call = backendCalls.find((c) => c.cmd === 'fs_write')
diff --git a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
index 9bf39949..d585710c 100644
--- a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
+++ b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
@@ -108,10 +108,16 @@ const fullWire = () => JSON.stringify(wireTools(codingCatalog()))
*
* Der codierende Zug ist der, den jeder Refactor bezahlt, und er bleibt
* gleich. Das ist der Grund, warum das Tor existiert.
+ *
+ * ── 30.09.2026: file_edit bekommt `edits` und `replace_all` ───────────────
+ * Kundenfall swift_maple90: jede Aenderung an derselben Datei war ein eigener
+ * Roundtrip mit vollem Kontext. `edits` buendelt sie in einen Aufruf. Die
+ * Beschreibung ist dafuer gekuerzt, der codierende Zug bleibt unter 7600;
+ * der volle Katalog steht bei 17.946 Zeichen, Deckel gemessen plus Rand.
*/
const CODING_CHAR_CEILING = 7600
const CODING_TOKEN_CEILING = 1730
-const FULL_CHAR_CEILING = 17880
+const FULL_CHAR_CEILING = 17980
const FULL_TOKEN_CEILING = 4090
describe('the coding step carries a catalog the diet actually shrank', () => {
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 6499e7a7..12b177d8 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -20,7 +20,7 @@ import {
buildCheckTasksExecutor,
buildMessageAgentExecutor,
} from '../agents/agent-task-tools'
-import { applyUniqueEdit } from '../../lib/surgical-edit'
+import { applyEdits, editsFromArgs, type EditSpec } from '../../lib/surgical-edit'
import { sliceFileReadResult } from '../../lib/file-read-window'
import { writeTodos, summarizeTodos } from '../../stores/todoStore'
import { isMlxImageHost, generateMlxImageDataUrl, listMlxImageModels, type MlxImageModel } from '../mlx-image'
@@ -266,17 +266,30 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
{
name: 'file_edit',
description:
- 'Make a SURGICAL edit to an existing file: replace old_string with new_string. PREFER it over file_write for any change to a file that exists. '
- + 'old_string must match EXACTLY ONCE: copy the exact text including indentation from a prior file_read and take enough surrounding lines to be unique. '
- + 'It FAILS with no change when old_string is missing or matches twice; then read the file and retry with more context.',
+ 'Edit an existing file, PREFER over file_write: replace old_string, copied from file_read with enough context to match ONE place, with new_string. '
+ + 'Several changes to one file: ONE call with `edits`. No match or several: nothing changes.',
inputSchema: {
type: 'object',
properties: {
- path: { type: 'string', description: 'Path to the existing file (absolute preferred)' },
- old_string: { type: 'string', description: 'Exact text to find — must occur exactly once in the file' },
- new_string: { type: 'string', description: 'Replacement text' },
+ path: { type: 'string', description: 'Existing file' },
+ old_string: { type: 'string', description: 'Text to find' },
+ new_string: { type: 'string', description: 'Replacement' },
+ replace_all: { type: 'boolean', description: 'Replace every match' },
+ edits: {
+ type: 'array',
+ description: 'In order, all or nothing',
+ items: {
+ type: 'object',
+ properties: {
+ old_string: { type: 'string', description: 'Text to find' },
+ new_string: { type: 'string', description: 'Replacement' },
+ replace_all: { type: 'boolean', description: 'Every match' },
+ },
+ required: ['old_string', 'new_string'],
+ },
+ },
},
- required: ['path', 'old_string', 'new_string'],
+ required: ['path'],
},
category: 'filesystem',
source: 'builtin',
@@ -673,16 +686,15 @@ async function executeFileEdit(args: ToolArgs, run?: AgentRunContext): Promise<s
const bad = missingArgs('file_edit', args, 'path')
if (bad) return bad
const path = argString(args, 'path')
- const oldString = argString(args, 'old_string')
- if (!oldString) return 'Error: file_edit requires a non-empty old_string. To create a new file use file_write.'
+ const edits = editsFromArgs(args)
+ if (edits.some((e) => !e.old_string)) return 'Error: file_edit requires a non-empty old_string. To create a new file use file_write.'
// `new_string` wie `content` bei file_write: '' ist ein gültiger Auftrag
// (Text löschen), ein fehlendes Feld nicht. `argString` zog beides zu ''
// zusammen — ein vergessenes Argument löschte damit still den Fundtext.
- if (typeof args.new_string !== 'string') {
+ if (edits.some((e) => e.new_string === undefined)) {
return 'file_edit: `new_string` is required — the replacement text. '
+ 'Pass "" to delete old_string. Nothing was changed; call file_edit again with it set.'
}
- const newString = args.new_string
// Read the CURRENT content (workspace-aware). file_edit only edits an
// existing text file — for a new file the model must use file_write.
@@ -695,8 +707,9 @@ async function executeFileEdit(args: ToolArgs, run?: AgentRunContext): Promise<s
if (data.encoding === 'binary' || data.encoding === 'base64') return `Error: file_edit cannot edit a binary file (${path}).`
const content = typeof data.content === 'string' ? data.content : ''
- const res = applyUniqueEdit(content, oldString, newString)
+ const res = applyEdits(content, edits as EditSpec[])
if (!res.ok) {
+ const which = res.failedIndex !== undefined ? ` (edit ${res.failedIndex + 1} of ${edits.length}, nothing was applied)` : ''
switch (res.reason) {
// Über DIESEN Pfad nicht mehr erreichbar (`old_string` wird oben geprüft,
// bevor gelesen wird); der Zweig bleibt, weil `EditFailReason` ein
@@ -706,16 +719,18 @@ async function executeFileEdit(args: ToolArgs, run?: AgentRunContext): Promise<s
case 'noop':
return 'Error: old_string and new_string are identical, nothing to change.'
case 'not_found':
- return `Error: old_string was not found in ${path}. Read the file and copy the exact text (including indentation) you want to replace.`
+ return `Error: old_string was not found in ${path}${which}. Read the file and copy the exact text you want to replace.`
case 'not_unique':
- return `Error: old_string matches ${res.matches} places in ${path}. Add surrounding lines so it uniquely identifies ONE location, then retry.`
+ return `Error: old_string matches ${res.matches} places in ${path}${which}. Add surrounding lines so it identifies ONE location, or set replace_all, then retry.`
default:
return 'Error: file_edit failed.'
}
}
const w = await backendCall<FsWriteResult>('fs_write', { path, content: res.content, ...chatCtx(run) })
- if (w.status === 'saved' && w.path) return `Edited ${w.path} (1 replacement).`
+ const n = res.replacements ?? 1
+ const note = res.fuzzyCount ? ` ${res.fuzzyCount === 1 ? 'One edit' : `${res.fuzzyCount} edits`} matched with indentation ignored; re-read before editing the same lines again.` : ''
+ if (w.status === 'saved' && w.path) return `Edited ${w.path} (${n} replacement${n === 1 ? '' : 's'}).${note}`
if (w.status === 'unchanged' && w.path) return `No change written to ${w.path} (content already matched).`
return JSON.stringify(w)
}
diff --git a/src/hooks/codex/staged-writes.ts b/src/hooks/codex/staged-writes.ts
index b24e51b5..7e8b6ee6 100644
--- a/src/hooks/codex/staged-writes.ts
+++ b/src/hooks/codex/staged-writes.ts
@@ -1,6 +1,6 @@
import { useStagedChangesStore } from '../../stores/stagedChangesStore'
import { computeUnifiedDiff } from '../../lib/diff'
-import { applyUniqueEdit } from '../../lib/surgical-edit'
+import { applyEdits, editsFromArgs } from '../../lib/surgical-edit'
import { findStagedForPath, stagedReadResult, stagedListingNote } from '../../lib/staged-overlay'
import { codexReadCtx, type CodexFsCtx, type CodexFileRead } from './workspace-fs'
import type { ToolArgs } from '../../api/mcp/types'
@@ -142,8 +142,7 @@ export function createStagedWriter(deps: StagedWriterDeps): StagedWriter {
const stageFileEdit = async (args: ToolArgs): Promise<string> => {
const path = String(args.path ?? '')
if (!path) return 'file_edit: missing path'
- const oldString = typeof args.old_string === 'string' ? args.old_string : ''
- const newString = typeof args.new_string === 'string' ? args.new_string : ''
+ const edits = editsFromArgs(args).map((e) => ({ ...e, new_string: e.new_string ?? '' }))
const resolvedPath = resolveStagedPath(path, workDir)
const stageReadCtx = codexReadCtx(workspaceSlug, workDir)
// Read-your-writes: chain onto the STAGED content when this path is
@@ -166,7 +165,7 @@ export function createStagedWriter(deps: StagedWriterDeps): StagedWriter {
return `file_edit: could not read ${path}. To create a new file use file_write.`
}
}
- const applied = applyUniqueEdit(baseContent, oldString, newString)
+ const applied = applyEdits(baseContent, edits)
if (!applied.ok) {
switch (applied.reason) {
case 'empty_old': return 'file_edit: old_string must be non-empty. Use file_write to create a new file.'
diff --git a/src/hooks/codex/tool-result-view.ts b/src/hooks/codex/tool-result-view.ts
index c6838f3f..39d0d23d 100644
--- a/src/hooks/codex/tool-result-view.ts
+++ b/src/hooks/codex/tool-result-view.ts
@@ -1,5 +1,5 @@
import { computeUnifiedDiff } from '../../lib/diff'
-import { applyUniqueEdit } from '../../lib/surgical-edit'
+import { applyEdits, editsFromArgs } from '../../lib/surgical-edit'
import type { ToolArgs } from '../../api/mcp/types'
/**
@@ -54,10 +54,9 @@ export function codexToolDiff({ toolName, path, oldText, args }: ToolDiffInput):
// reconstruct the new content from the pre-read + the unique
// replacement to attach a real diff. If the edit did not apply
// uniquely the executor already returned an error; skip the diff.
- const applied = applyUniqueEdit(
+ const applied = applyEdits(
oldText,
- typeof args.old_string === 'string' ? args.old_string : '',
- typeof args.new_string === 'string' ? args.new_string : '',
+ editsFromArgs(args).map((e) => ({ ...e, new_string: e.new_string ?? '' })),
)
return applied.ok
? computeUnifiedDiff(path ?? '', oldText, applied.content ?? '') || undefined
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 691fdc8c..824624b7 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -163,7 +163,7 @@ Work in batches. Every step resends the whole conversation, so each round trip c
Rules:
- Always read a file before modifying it
-- To CHANGE part of an existing file, use file_edit (replace a UNIQUE old_string with new_string), it is far cheaper and safer than rewriting the whole file with file_write, and never truncates a large file. Use file_write only to CREATE a new file or fully replace one. If file_edit reports the old_string is missing or not unique, read the file and retry with more surrounding lines.
+- To CHANGE part of an existing file, use file_edit (replace a UNIQUE old_string with new_string), it is far cheaper and safer than rewriting the whole file with file_write, and never truncates a large file. Use file_write only to CREATE a new file or fully replace one. Several changes to the same file go into ONE file_edit call as \`edits\`. If file_edit reports the old_string is missing or not unique, read the file and retry with more surrounding lines.
- PATHS: use paths relative to the working directory shown below (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`), that escapes the workspace and fails.
- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool
- If a command fails, diagnose and retry with a different approach, don't hand back to the user unless truly stuck
diff --git a/src/lib/__tests__/surgical-edit-tolerant.test.ts b/src/lib/__tests__/surgical-edit-tolerant.test.ts
new file mode 100644
index 00000000..19f79040
--- /dev/null
+++ b/src/lib/__tests__/surgical-edit-tolerant.test.ts
@@ -0,0 +1,90 @@
+/**
+ * file_edit, the three additions of 01.10.2026: a whitespace-tolerant line
+ * match when the exact text is not there, replace_all, and several edits in
+ * one call. Every failed edit on a paid provider meant "read again, retry",
+ * two more full-context round trips.
+ *
+ * Run: npx vitest run src/lib/__tests__/surgical-edit-tolerant.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { applyUniqueEdit, applyEdits, editsFromArgs } from '../surgical-edit'
+
+const FILE = [
+ 'export function add(a, b) {',
+ ' const sum = a + b',
+ ' return sum',
+ '}',
+ '',
+].join('\n')
+
+describe('whitespace-tolerant match', () => {
+ it('finds the lines when the model got the indentation wrong, and keeps the file level', () => {
+ const r = applyUniqueEdit(FILE, 'const sum = a + b\nreturn sum', 'const total = a + b\nreturn total')
+ expect(r.ok).toBe(true)
+ expect(r.fuzzy).toBe(true)
+ expect(r.content).toBe(FILE.replace(' const sum = a + b\n return sum', ' const total = a + b\n return total'))
+ })
+
+ it('shifts a differently indented new_string to the file indentation', () => {
+ const r = applyUniqueEdit(FILE, '\tconst sum = a + b', '\tconst sum = a + b\n\tconsole.log(sum)')
+ expect(r.fuzzy).toBe(true)
+ expect(r.content).toContain(' const sum = a + b\n console.log(sum)\n return sum')
+ })
+
+ it('keeps CRLF files CRLF', () => {
+ const crlf = FILE.replace(/\n/g, '\r\n')
+ const r = applyUniqueEdit(crlf, 'return sum', 'return sum * 1')
+ expect(r.content).toBe(crlf.replace('return sum', 'return sum * 1'))
+ const fuzzy = applyUniqueEdit(crlf, 'const sum = a + b\nreturn sum', 'return a + b')
+ expect(fuzzy.ok).toBe(true)
+ expect(fuzzy.content).not.toMatch(/(?<!\r)\n/)
+ })
+
+ it('refuses when the tolerant match is ambiguous', () => {
+ const twice = 'if (x) {\n go()\n}\nif (x) {\n go()\n}\n'
+ expect(applyUniqueEdit(twice, 'go()', 'stop()').reason).toBe('not_unique')
+ expect(applyUniqueEdit(twice, ' go() ', 'stop()').reason).toBe('not_unique')
+ })
+
+ it('still says not_found when nothing matches', () => {
+ expect(applyUniqueEdit(FILE, 'return difference', 'x').reason).toBe('not_found')
+ })
+})
+
+describe('replace_all', () => {
+ it('replaces every occurrence', () => {
+ const r = applyUniqueEdit('foo(); foo(); bar()', 'foo', 'baz', true)
+ expect(r).toMatchObject({ ok: true, content: 'baz(); baz(); bar()', matches: 2 })
+ })
+ it('without it, two matches stay refused', () => {
+ expect(applyUniqueEdit('foo(); foo()', 'foo', 'baz').reason).toBe('not_unique')
+ })
+})
+
+describe('several edits in one call', () => {
+ it('applies them in order', () => {
+ const r = applyEdits(FILE, [
+ { old_string: 'add(a, b)', new_string: 'add(a, b, c = 0)' },
+ { old_string: 'a + b', new_string: 'a + b + c' },
+ ])
+ expect(r.ok).toBe(true)
+ expect(r.content).toContain('add(a, b, c = 0)')
+ expect(r.content).toContain('const sum = a + b + c')
+ })
+
+ it('is all or nothing and names the failing edit', () => {
+ const r = applyEdits(FILE, [
+ { old_string: 'add(a, b)', new_string: 'plus(a, b)' },
+ { old_string: 'does not exist', new_string: 'x' },
+ ])
+ expect(r).toMatchObject({ ok: false, reason: 'not_found', failedIndex: 1 })
+ expect(r.content).toBeUndefined()
+ })
+
+ it('reads both argument shapes', () => {
+ expect(editsFromArgs({ old_string: 'a', new_string: 'b' })).toEqual([{ old_string: 'a', new_string: 'b', replace_all: false }])
+ expect(editsFromArgs({ edits: [{ old_string: 'a', new_string: 'b', replace_all: true }] }))
+ .toEqual([{ old_string: 'a', new_string: 'b', replace_all: true }])
+ expect(editsFromArgs({ old_string: 'a' })[0].new_string).toBeUndefined()
+ })
+})
diff --git a/src/lib/surgical-edit.ts b/src/lib/surgical-edit.ts
index 5a33c218..a88b9de4 100644
--- a/src/lib/surgical-edit.ts
+++ b/src/lib/surgical-edit.ts
@@ -1,7 +1,8 @@
/**
* Surgical edit primitive — the core of the `file_edit` tool (2.5.9, M1).
*
- * Replaces exactly ONE unique occurrence of old_string with new_string, or
+ * Replaces exactly ONE unique occurrence of old_string with new_string (or
+ * every occurrence with replace_all, or several edits in one call), or
* reports why it could not (empty / no-op / not found / not unique). This is
* the small-model-friendly alternative to full-file rewrites: the model sends
* only the lines it wants changed, so editing a 2000-line file costs a few
@@ -22,6 +23,8 @@ export interface EditOutcome {
matches: number
/** Machine-usable reason when !ok. */
reason?: EditFailReason
+ /** The exact text was not there; the whitespace-tolerant line match was used. */
+ fuzzy?: boolean
}
/**
@@ -85,19 +88,76 @@ export function countOccurrences(haystack: string, needle: string): number {
}
/**
- * Apply a unique-match replacement. `oldString` must occur exactly once for the
- * edit to succeed — this is what makes surgical edits safe: an ambiguous match
- * is refused rather than silently changing the wrong (or every) occurrence.
+ * Whitespace-tolerant fallback for a missing exact match (01.10.2026).
+ *
+ * Open models copy code back with the indentation off by a level, tabs turned
+ * into spaces or a trailing space lost. The exact search then fails, and the
+ * only way on was "read the file again and retry", two more full-context
+ * round trips on a paid provider. opencode, Cline and Aider all fall back to a
+ * line-wise comparison for this reason.
+ *
+ * Rule, kept narrow on purpose: compare line by line with leading and trailing
+ * whitespace ignored, blank edge lines of old_string dropped, and accept only
+ * when exactly ONE window of the file matches. The matched lines are replaced
+ * whole, and new_string is shifted from old_string's indentation to the
+ * file's, so the result sits at the file's own level.
*/
-export function applyUniqueEdit(content: string, oldString: string, newString: string): EditOutcome {
+function fuzzyLineMatch(contentLf: string, oldLf: string, newLf: string):
+ { ok: true; content: string } | { ok: false; matches: number } {
+ const oldLines = oldLf.split('\n')
+ while (oldLines.length && oldLines[0].trim() === '') oldLines.shift()
+ while (oldLines.length && oldLines[oldLines.length - 1].trim() === '') oldLines.pop()
+ if (oldLines.length === 0 || oldLines.join('').trim().length < 2) return { ok: false, matches: 0 }
+ const fileLines = contentLf.split('\n')
+ const want = oldLines.map((l) => l.trim())
+ const hits: number[] = []
+ for (let i = 0; i + want.length <= fileLines.length; i++) {
+ let same = true
+ for (let j = 0; j < want.length; j++) {
+ if (fileLines[i + j].trim() !== want[j]) { same = false; break }
+ }
+ if (same) hits.push(i)
+ }
+ if (hits.length !== 1) return { ok: false, matches: hits.length }
+ const at = hits[0]
+ const indentOf = (l: string) => l.match(/^[ \t]*/)![0]
+ const fileIndent = indentOf(fileLines[at])
+ const oldIndent = indentOf(oldLines[0])
+ let newLines = newLf.split('\n')
+ if (fileIndent !== oldIndent && newLines.every((l) => l.trim() === '' || l.startsWith(oldIndent))) {
+ newLines = newLines.map((l) => (l.trim() === '' ? l : fileIndent + l.slice(oldIndent.length)))
+ }
+ const out = [...fileLines.slice(0, at), ...newLines, ...fileLines.slice(at + want.length)]
+ return { ok: true, content: out.join('\n') }
+}
+
+/**
+ * Apply one replacement. By default `oldString` must occur exactly once: an
+ * ambiguous match is refused rather than silently changing the wrong spot.
+ * `replaceAll` replaces every exact occurrence instead (renames). Without an
+ * exact match the whitespace-tolerant line match above gets one try.
+ */
+export function applyUniqueEdit(content: string, oldString: string, newString: string, replaceAll = false): EditOutcome {
if (oldString === '') return { ok: false, matches: 0, reason: 'empty_old' }
const { lf: contentLf, map } = lfWithMap(content)
const oldLf = toLf(oldString)
const newLf = toLf(newString)
const matches = countOccurrences(contentLf, oldLf)
if (oldLf === newLf) return { ok: false, matches, reason: 'noop' }
- if (matches === 0) return { ok: false, matches: 0, reason: 'not_found' }
- if (matches > 1) return { ok: false, matches, reason: 'not_unique' }
+ if (matches === 0) {
+ const fuzzy = fuzzyLineMatch(contentLf, oldLf, newLf)
+ if (!fuzzy.ok) {
+ return fuzzy.matches > 1
+ ? { ok: false, matches: fuzzy.matches, reason: 'not_unique' }
+ : { ok: false, matches: 0, reason: 'not_found' }
+ }
+ return { ok: true, content: withEol(fuzzy.content, eolOf(content)), matches: 1, fuzzy: true }
+ }
+ if (matches > 1 && !replaceAll) return { ok: false, matches, reason: 'not_unique' }
+ if (replaceAll) {
+ const updated = withEol(contentLf.split(oldLf).join(newLf), eolOf(content))
+ return { ok: true, content: updated, matches }
+ }
// Exactly one occurrence. Cut it out of the ORIGINAL by index instead of
// running a replace over the normalized copy: that keeps every byte outside
// the match untouched, so a three-line edit stays a three-line diff. Slicing
@@ -110,3 +170,55 @@ export function applyUniqueEdit(content: string, oldString: string, newString: s
content.slice(map[start + oldLf.length])
return { ok: true, content: updated, matches: 1 }
}
+
+/** One replacement as the tool receives it. */
+export interface EditSpec {
+ old_string: string
+ new_string: string
+ replace_all?: boolean
+}
+
+/**
+ * The edits one file_edit call carries: an `edits` array, or the single
+ * old_string/new_string pair. A missing new_string stays missing (undefined)
+ * so the caller can refuse it instead of silently deleting the found text.
+ */
+export function editsFromArgs(args: Record<string, unknown>): Array<{ old_string: string; new_string: string | undefined; replace_all: boolean }> {
+ const one = (e: Record<string, unknown>) => ({
+ old_string: typeof e.old_string === 'string' ? e.old_string : '',
+ new_string: typeof e.new_string === 'string' ? e.new_string : undefined,
+ replace_all: e.replace_all === true,
+ })
+ if (Array.isArray(args.edits) && args.edits.length > 0) {
+ return args.edits.filter((e): e is Record<string, unknown> => !!e && typeof e === 'object').map(one)
+ }
+ return [one(args)]
+}
+
+export interface MultiEditOutcome extends EditOutcome {
+ /** Which edit failed (0-based), when !ok and there was more than one. */
+ failedIndex?: number
+ /** How many edits needed the whitespace-tolerant match. */
+ fuzzyCount?: number
+ /** Total replacements made. */
+ replacements?: number
+}
+
+/**
+ * Apply every edit in order on the running result, all or nothing: one failed
+ * edit leaves the file untouched, so a half-applied change never lands.
+ */
+export function applyEdits(content: string, edits: EditSpec[]): MultiEditOutcome {
+ let cur = content
+ let fuzzyCount = 0
+ let replacements = 0
+ for (let i = 0; i < edits.length; i++) {
+ const e = edits[i]
+ const r = applyUniqueEdit(cur, e.old_string, e.new_string, e.replace_all === true)
+ if (!r.ok) return { ...r, failedIndex: edits.length > 1 ? i : undefined }
+ cur = r.content ?? cur
+ if (r.fuzzy) fuzzyCount++
+ replacements += r.matches
+ }
+ return { ok: true, content: cur, matches: replacements, fuzzyCount, replacements }
+}