From d45a90e793a4d7f1216aff03f8c9c25fe2211d79 Mon Sep 17 00:00:00 2001 From: VIOLETee0 <1842771550@qq.com> Date: Wed, 2 Dec 2026 22:24:58 +0800 Subject: [PATCH] Reject missing anchors before applying file patches --- sdk/src/__tests__/apply-patch.test.ts | 28 ++++++++++++++++++++++++++- sdk/src/tools/apply-patch.ts | 3 +++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/sdk/src/__tests__/apply-patch.test.ts b/sdk/src/__tests__/apply-patch.test.ts index e3c20e8e56..b387f072bf 100644 --- a/sdk/src/__tests__/apply-patch.test.ts +++ b/sdk/src/__tests__/apply-patch.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, test } from 'bun:test' +import path from 'node:path' import { createMockFs } from '@codebuff/common/testing/mocks/filesystem' +import { describe, expect, test } from 'bun:test' import { applyPatchTool } from '../tools/apply-patch' @@ -187,6 +188,31 @@ describe('applyPatchTool', () => { expect(updated).toBe(['before', 'target', 'inserted', 'after', ''].join('\n')) }) + test('rejects a missing anchor without editing matching context elsewhere', async () => { + const original = 'function other() {\n return false\n}\n' + const cwd = path.resolve('/repo') + const file = path.join(cwd, 'src/file.ts') + const fs = createMockFs({ files: { [file]: original } }) + + const result = await applyPatchTool({ + parameters: { + operation: { + type: 'update_file', + path: 'src/file.ts', + diff: '@@ function missing() {\n- return false\n+ return true\n', + }, + }, + cwd, + fs, + }) + + expect(result[0]).toMatchObject({ + type: 'json', + value: { errorMessage: expect.stringContaining('function missing() {') }, + }) + expect(await fs.readFile(file, 'utf-8')).toBe(original) + }) + test('applies update patch when file has CRLF line endings', async () => { const fs = createMockFs({ files: { diff --git a/sdk/src/tools/apply-patch.ts b/sdk/src/tools/apply-patch.ts index 4e7ae73b5b..c297776838 100644 --- a/sdk/src/tools/apply-patch.ts +++ b/sdk/src/tools/apply-patch.ts @@ -168,6 +168,9 @@ function advanceCursorToAnchor( break } } + if (!found) { + throw new Error(`Anchor not found: ${anchor}`) + } } return cursor