Skip to content

Commit 236cfcb

Browse files
authored
fix(opencode): prevent destructive edit matches (anomalyco#30932)
1 parent a8adfb6 commit 236cfcb

2 files changed

Lines changed: 89 additions & 17 deletions

File tree

‎packages/opencode/src/tool/edit.ts‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,14 @@ export const EditTool = Tool.define(
8989
Effect.gen(function* () {
9090
if (params.oldString === "") {
9191
const existed = yield* afs.existsSafe(filePath)
92-
const source = existed ? yield* Bom.readFile(afs, filePath) : { bom: false, text: "" }
92+
if (existed) {
93+
throw new Error(
94+
"oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.",
95+
)
96+
}
9397
const next = Bom.split(params.newString)
94-
const desiredBom = source.bom || next.bom
95-
contentOld = source.text
98+
const desiredBom = next.bom
99+
contentOld = ""
96100
contentNew = next.text
97101
diff = trimDiff(createTwoFilesPatch(filePath, filePath, contentOld, contentNew))
98102
yield* ctx.ask({
@@ -111,7 +115,7 @@ export const EditTool = Tool.define(
111115
yield* events.publish(FileSystem.Event.Edited, { file: filePath })
112116
yield* events.publish(Watcher.Event.Updated, {
113117
file: filePath,
114-
event: existed ? "change" : "add",
118+
event: "add",
115119
})
116120
return
117121
}
@@ -213,8 +217,8 @@ export const EditTool = Tool.define(
213217
export type Replacer = (content: string, find: string) => Generator<string, void, unknown>
214218

215219
// Similarity thresholds for block anchor fallback matching
216-
const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.0
217-
const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.3
220+
const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.65
221+
const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.65
218222

219223
/**
220224
* Levenshtein distance algorithm implementation
@@ -296,6 +300,7 @@ export const BlockAnchorReplacer: Replacer = function* (content, find) {
296300
const firstLineSearch = searchLines[0].trim()
297301
const lastLineSearch = searchLines[searchLines.length - 1].trim()
298302
const searchBlockSize = searchLines.length
303+
const maxLineDelta = Math.max(1, Math.floor(searchBlockSize * 0.25))
299304

300305
// Collect all candidate positions where both anchors match
301306
const candidates: Array<{ startLine: number; endLine: number }> = []
@@ -307,7 +312,10 @@ export const BlockAnchorReplacer: Replacer = function* (content, find) {
307312
// Look for the matching last line after this first line
308313
for (let j = i + 2; j < originalLines.length; j++) {
309314
if (originalLines[j].trim() === lastLineSearch) {
310-
candidates.push({ startLine: i, endLine: j })
315+
const actualBlockSize = j - i + 1
316+
if (Math.abs(actualBlockSize - searchBlockSize) <= maxLineDelta) {
317+
candidates.push({ startLine: i, endLine: j })
318+
}
311319
break // Only match the first occurrence of the last line
312320
}
313321
}
@@ -324,7 +332,7 @@ export const BlockAnchorReplacer: Replacer = function* (content, find) {
324332
const actualBlockSize = endLine - startLine + 1
325333

326334
let similarity = 0
327-
let linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2) // Middle lines only
335+
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2) // Middle lines only
328336

329337
if (linesToCheck > 0) {
330338
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
@@ -373,7 +381,7 @@ export const BlockAnchorReplacer: Replacer = function* (content, find) {
373381
const actualBlockSize = endLine - startLine + 1
374382

375383
let similarity = 0
376-
let linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2) // Middle lines only
384+
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2) // Middle lines only
377385

378386
if (linesToCheck > 0) {
379387
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
@@ -675,6 +683,11 @@ export function replace(content: string, oldString: string, newString: string, r
675683
if (oldString === newString) {
676684
throw new Error("No changes to apply: oldString and newString are identical.")
677685
}
686+
if (oldString === "") {
687+
throw new Error(
688+
"oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.",
689+
)
690+
}
678691

679692
let notFound = true
680693

@@ -693,6 +706,11 @@ export function replace(content: string, oldString: string, newString: string, r
693706
const index = content.indexOf(search)
694707
if (index === -1) continue
695708
notFound = false
709+
if (isDisproportionateMatch(search, oldString)) {
710+
throw new Error(
711+
"Refusing replacement because the matched span is much larger than oldString. Re-read the file and provide the full exact oldString for the intended replacement.",
712+
)
713+
}
696714
if (replaceAll) {
697715
return content.replaceAll(search, newString)
698716
}
@@ -709,3 +727,11 @@ export function replace(content: string, oldString: string, newString: string, r
709727
}
710728
throw new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")
711729
}
730+
731+
function isDisproportionateMatch(search: string, oldString: string) {
732+
const oldLines = oldString.split("\n").length
733+
const searchLines = search.split("\n").length
734+
if (searchLines >= Math.max(oldLines + 3, oldLines * 2)) return true
735+
if (oldLines === 1) return false
736+
return search.trim().length > Math.max(oldString.trim().length + 500, oldString.trim().length * 4)
737+
}

‎packages/opencode/test/tool/edit.test.ts‎

Lines changed: 54 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -106,21 +106,20 @@ describe("tool.edit", () => {
106106
}),
107107
)
108108

109-
it.instance("preserves BOM when oldString is empty on existing files", () =>
109+
it.instance("rejects empty oldString on existing files and leaves content unchanged", () =>
110110
Effect.gen(function* () {
111111
const test = yield* TestInstance
112112
const filepath = path.join(test.directory, "existing.cs")
113113
const bom = String.fromCharCode(0xfeff)
114-
yield* put(filepath, `${bom}using System;\n`)
114+
const original = `${bom}using System;\n`
115+
yield* put(filepath, original)
115116

116-
const result = yield* run({ filePath: filepath, oldString: "", newString: "using Up;\n" })
117-
118-
expect(result.metadata.diff).toContain("-using System;")
119-
expect(result.metadata.diff).toContain("+using Up;")
117+
expect((yield* fail({ filePath: filepath, oldString: "", newString: "using Up;\n" })).message).toContain(
118+
"oldString cannot be empty",
119+
)
120120

121121
const content = yield* loadRaw(filepath)
122-
expect(content.charCodeAt(0)).toBe(0xfeff)
123-
expect(content.slice(1)).toBe("using Up;\n")
122+
expect(content).toBe(original)
124123
}),
125124
)
126125

@@ -213,6 +212,53 @@ describe("tool.edit", () => {
213212
}),
214213
)
215214

215+
it.instance("rejects loose block-anchor matches and leaves content unchanged", () =>
216+
Effect.gen(function* () {
217+
const test = yield* TestInstance
218+
const filepath = path.join(test.directory, "file.ts")
219+
const original = [
220+
"function configure() {",
221+
" keepImportantState()",
222+
" removeAllUserData()",
223+
" archiveBackups()",
224+
" auditLog()",
225+
"}",
226+
].join("\n")
227+
yield* put(filepath, original)
228+
229+
expect(
230+
(
231+
yield* fail({
232+
filePath: filepath,
233+
oldString: ["function configure() {", " const enabled = true", "}"].join("\n"),
234+
newString: ["function configure() {", " const enabled = false", "}"].join("\n"),
235+
})
236+
).message,
237+
).toContain("Could not find oldString")
238+
expect(yield* load(filepath)).toBe(original)
239+
}),
240+
)
241+
242+
it.instance("rejects block-anchor matches with unrelated middle content", () =>
243+
Effect.gen(function* () {
244+
const test = yield* TestInstance
245+
const filepath = path.join(test.directory, "file.ts")
246+
const original = ["function configure() {", " removeAllUserData()", "}"].join("\n")
247+
yield* put(filepath, original)
248+
249+
expect(
250+
(
251+
yield* fail({
252+
filePath: filepath,
253+
oldString: ["function configure() {", " const enabled = true", "}"].join("\n"),
254+
newString: ["function configure() {", " const enabled = false", "}"].join("\n"),
255+
})
256+
).message,
257+
).toContain("Could not find oldString")
258+
expect(yield* load(filepath)).toBe(original)
259+
}),
260+
)
261+
216262
it.instance("replaces all occurrences with replaceAll option", () =>
217263
Effect.gen(function* () {
218264
const test = yield* TestInstance

0 commit comments

Comments
 (0)