-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfile_edit_tool.cpp
More file actions
545 lines (479 loc) · 20.3 KB
/
Copy pathfile_edit_tool.cpp
File metadata and controls
545 lines (479 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#include "file_edit_tool.hpp"
#include "mtime_tracker.hpp"
#include "diff_utils.hpp"
#include "tool_icons.hpp"
#include "lsp/lsp_diagnostics.hpp"
#include "utils/logger.hpp"
#include "utils/tool_args_parser.hpp"
#include "utils/tool_errors.hpp"
#include "utils/file_operations.hpp"
#include "utils/text_file_buffer.hpp"
#include "utils/utf8_path.hpp"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <exception>
#include <filesystem>
#include <optional>
#include <sstream>
#include <vector>
namespace acecode {
namespace {
static bool ends_with_ipynb(const std::string& path) {
std::string lower = path;
std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
const std::string suffix = ".ipynb";
return lower.size() >= suffix.size() &&
lower.compare(lower.size() - suffix.size(), suffix.size(), suffix) == 0;
}
static bool is_blank_content(const std::string& content) {
for (unsigned char c : content) {
if (!std::isspace(c)) return false;
}
return true;
}
static std::string ascii_lower_trim(std::string s) {
auto is_space = [](unsigned char c) { return std::isspace(c) != 0; };
while (!s.empty() && is_space(static_cast<unsigned char>(s.front()))) s.erase(s.begin());
while (!s.empty() && is_space(static_cast<unsigned char>(s.back()))) s.pop_back();
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
}
static bool parse_semantic_bool(const std::string& arguments_json, const std::string& key, bool default_value) {
auto j = nlohmann::json::parse(arguments_json, nullptr, false);
if (j.is_discarded() || !j.contains(key)) return default_value;
const auto& v = j[key];
if (v.is_boolean()) return v.get<bool>();
if (v.is_number_integer()) return v.get<int>() != 0;
if (v.is_string()) {
const std::string value = ascii_lower_trim(v.get<std::string>());
if (value == "true" || value == "1" || value == "yes" || value == "on") return true;
if (value == "false" || value == "0" || value == "no" || value == "off") return false;
}
return default_value;
}
static bool file_uses_crlf(const std::string& content) {
return content.find("\r\n") != std::string::npos;
}
static std::string lf_to_crlf(std::string value) {
std::string out;
out.reserve(value.size());
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '\n' && (i == 0 || value[i - 1] != '\r')) {
out += "\r\n";
} else {
out += value[i];
}
}
return out;
}
struct QuoteNormalizedText {
std::string text;
std::vector<size_t> start_offsets;
std::vector<size_t> end_offsets;
};
static bool starts_with_at(const std::string& value, size_t pos, const std::string& needle) {
return pos + needle.size() <= value.size() &&
value.compare(pos, needle.size(), needle) == 0;
}
static QuoteNormalizedText normalize_quotes_with_offsets(const std::string& value) {
static const std::string left_single = u8"‘";
static const std::string right_single = u8"’";
static const std::string left_double = u8"“";
static const std::string right_double = u8"”";
QuoteNormalizedText out;
out.text.reserve(value.size());
out.start_offsets.reserve(value.size());
out.end_offsets.reserve(value.size());
for (size_t i = 0; i < value.size();) {
std::string replacement;
size_t next = i + 1;
if (starts_with_at(value, i, left_single) || starts_with_at(value, i, right_single)) {
replacement = "'";
next = i + left_single.size();
} else if (starts_with_at(value, i, left_double) || starts_with_at(value, i, right_double)) {
replacement = "\"";
next = i + left_double.size();
} else {
replacement.assign(1, value[i]);
}
for (char c : replacement) {
out.text.push_back(c);
out.start_offsets.push_back(i);
out.end_offsets.push_back(next);
}
i = next;
}
return out;
}
static std::string normalize_quotes(const std::string& value) {
return normalize_quotes_with_offsets(value).text;
}
static std::optional<std::string> find_actual_string_by_quotes(
const std::string& content,
const std::string& search
) {
if (search.empty()) return std::nullopt;
auto normalized_content = normalize_quotes_with_offsets(content);
const std::string normalized_search = normalize_quotes(search);
const size_t found = normalized_content.text.find(normalized_search);
if (found == std::string::npos || normalized_search.empty()) {
return std::nullopt;
}
const size_t last = found + normalized_search.size() - 1;
if (found >= normalized_content.start_offsets.size() ||
last >= normalized_content.end_offsets.size()) {
return std::nullopt;
}
const size_t start = normalized_content.start_offsets[found];
const size_t end = normalized_content.end_offsets[last];
if (end < start || end > content.size()) return std::nullopt;
return content.substr(start, end - start);
}
static bool is_ascii_letter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static bool is_opening_quote_context(const std::string& value, size_t index) {
if (index == 0) return true;
const char prev = value[index - 1];
return prev == ' ' || prev == '\t' || prev == '\n' || prev == '\r' ||
prev == '(' || prev == '[' || prev == '{';
}
static std::string apply_curly_double_quotes(const std::string& value) {
static const std::string left_double = u8"“";
static const std::string right_double = u8"”";
std::string out;
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '"') {
out += is_opening_quote_context(value, i) ? left_double : right_double;
} else {
out.push_back(value[i]);
}
}
return out;
}
static std::string apply_curly_single_quotes(const std::string& value) {
static const std::string left_single = u8"‘";
static const std::string right_single = u8"’";
std::string out;
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '\'') {
const bool contraction =
i > 0 &&
i + 1 < value.size() &&
is_ascii_letter(value[i - 1]) &&
is_ascii_letter(value[i + 1]);
if (contraction) {
out += right_single;
} else {
out += is_opening_quote_context(value, i) ? left_single : right_single;
}
} else {
out.push_back(value[i]);
}
}
return out;
}
static std::string preserve_quote_style(
const std::string& requested_old,
const std::string& actual_old,
const std::string& requested_new
) {
if (requested_old == actual_old) return requested_new;
static const std::string left_single = u8"‘";
static const std::string right_single = u8"’";
static const std::string left_double = u8"“";
static const std::string right_double = u8"”";
std::string result = requested_new;
if (actual_old.find(left_double) != std::string::npos ||
actual_old.find(right_double) != std::string::npos) {
result = apply_curly_double_quotes(result);
}
if (actual_old.find(left_single) != std::string::npos ||
actual_old.find(right_single) != std::string::npos) {
result = apply_curly_single_quotes(result);
}
return result;
}
struct MatchPlan {
std::string actual_old;
std::string actual_new;
};
static std::optional<MatchPlan> build_match_plan(
const std::string& content,
const std::string& requested_old,
const std::string& requested_new
) {
if (content.find(requested_old) != std::string::npos) {
return MatchPlan{requested_old, requested_new};
}
// 模型常按 LF 组织多行字符串;CRLF 文件要在匹配和替换两端同步适配。
if (file_uses_crlf(content) && requested_old.find('\n') != std::string::npos) {
const std::string old_crlf = lf_to_crlf(requested_old);
const std::string new_crlf = lf_to_crlf(requested_new);
if (content.find(old_crlf) != std::string::npos) {
return MatchPlan{old_crlf, new_crlf};
}
if (auto actual = find_actual_string_by_quotes(content, old_crlf)) {
return MatchPlan{*actual, preserve_quote_style(old_crlf, *actual, new_crlf)};
}
}
// ClaudeCode 的 Edit 允许 ASCII 引号命中 curly quote;这里保持同样的宽容度,
// 但最终仍替换文件中的真实字节范围。
if (auto actual = find_actual_string_by_quotes(content, requested_old)) {
return MatchPlan{*actual, preserve_quote_style(requested_old, *actual, requested_new)};
}
return std::nullopt;
}
static size_t count_occurrences(const std::string& content, const std::string& needle) {
if (needle.empty()) return 0;
size_t count = 0;
size_t pos = 0;
while ((pos = content.find(needle, pos)) != std::string::npos) {
++count;
pos += needle.size();
}
return count;
}
static std::string replace_occurrences(
const std::string& content,
const std::string& needle,
const std::string& replacement,
bool replace_all
) {
const size_t first = content.find(needle);
if (first == std::string::npos) return content;
if (!replace_all) {
std::string out = content;
out.replace(first, needle.size(), replacement);
return out;
}
std::string out;
out.reserve(content.size());
size_t pos = 0;
size_t found = 0;
while ((found = content.find(needle, pos)) != std::string::npos) {
out.append(content, pos, found - pos);
out += replacement;
pos = found + needle.size();
}
out.append(content, pos, std::string::npos);
return out;
}
static ToolResult run_validated_write(
const std::string& file_path,
bool file_existed,
const std::string& old_content,
const std::string& new_content,
const TextFileMetadata& metadata,
const ToolContext& ctx
) {
auto before_write = [&](const std::string& path) {
if (ctx.track_file_write_before) {
try {
ctx.track_file_write_before(path);
} catch (const std::exception& e) {
LOG_WARN(std::string("file_edit checkpoint hook failed: ") + e.what());
} catch (...) {
LOG_WARN("file_edit checkpoint hook failed with unknown error");
}
}
};
auto write_result = safe_write_text_file(file_path, new_content, metadata, before_write);
if (!write_result.success) {
return ToolResult{write_result.error, false};
}
MtimeTracker::instance().record_write(file_path, new_content);
// 同时产出结构化 hunk + 文本 diff,保证 TUI 彩色渲染和 LLM 下一轮阅读同源。
DiffStats stats;
std::string diff = generate_unified_diff(old_content, new_content, file_path, stats);
auto structured = generate_structured_diff(old_content, new_content, file_path);
ToolSummary summary;
summary.verb = file_existed ? "Edited" : "Created";
summary.object = file_path;
summary.metrics.emplace_back("+", std::to_string(stats.additions));
summary.metrics.emplace_back("-", std::to_string(stats.deletions));
summary.icon = tool_icon("file_edit");
ToolResult r{(file_existed ? "Edited " : "Created file: ") + file_path + "\n\n" + diff, true};
r.summary = std::move(summary);
r.hunks = std::move(structured);
// LSP 编辑后诊断:未启用/无匹配 server 时零开销;有 ERROR 时把
// <diagnostics> 块附加到输出,模型当场看到并修复(openspec add-lsp-service)。
lsp::append_diagnostics_block(r.output, file_path, ctx.abort_flag, ctx.cwd);
return r;
}
static ToolResult make_old_string_not_found_result(const std::string& file_path,
const std::string& normalized_content,
const std::string& requested_old) {
std::ostringstream oss;
oss << ToolErrors::string_not_found(file_path) << "\n"
<< "ACECode matches old_string against UTF-8 text with LF line endings. "
<< "Re-read the relevant lines and retry with the exact current text "
<< "instead of shell or Python writes.";
std::string first_line = normalize_text_to_lf(requested_old);
size_t nl = first_line.find('\n');
if (nl != std::string::npos) first_line.resize(nl);
while (!first_line.empty() && std::isspace(static_cast<unsigned char>(first_line.front()))) first_line.erase(first_line.begin());
while (!first_line.empty() && std::isspace(static_cast<unsigned char>(first_line.back()))) first_line.pop_back();
if (!first_line.empty()) {
size_t pos = normalized_content.find(first_line);
if (pos != std::string::npos) {
int line = 1;
for (size_t i = 0; i < pos; ++i) {
if (normalized_content[i] == '\n') ++line;
}
oss << "\nA substring from old_string appears near line " << line
<< ". Re-read a narrow range around that line and include more surrounding text.";
}
}
return ToolResult{oss.str(), false};
}
} // namespace
static ToolResult execute_file_edit(const std::string& arguments_json, const ToolContext& ctx) {
// Parse arguments
ToolArgsParser parser(arguments_json);
if (parser.has_error()) {
return ToolResult{parser.error(), false};
}
std::string file_path = parser.get_or<std::string>("file_path", "");
std::string old_string = parser.get_or<std::string>("old_string", "");
std::string new_string = parser.get_or<std::string>("new_string", "");
bool replace_all = parse_semantic_bool(arguments_json, "replace_all", false);
const auto raw_args = nlohmann::json::parse(arguments_json, nullptr, false);
const bool has_legacy_range_args = raw_args.is_object() &&
(raw_args.contains("start_line") ||
raw_args.contains("end_line") ||
raw_args.contains("expected_hash") ||
raw_args.contains("read_id"));
if (file_path.empty()) {
return ToolResult{ToolErrors::missing_parameter("file_path"), false};
}
const auto resolved_path = ctx.resolve_scratch_path_alias(file_path);
if (!resolved_path.success) {
return ToolResult{resolved_path.error, false};
}
file_path = resolved_path.path;
if (has_legacy_range_args) {
return ToolResult{ToolErrors::legacy_range_edit_arguments(file_path), false};
}
if (old_string == new_string) {
return ToolResult{ToolErrors::no_changes_to_make(), false};
}
if (ends_with_ipynb(file_path)) {
return ToolResult{ToolErrors::notebook_edit_required(file_path), false};
}
LOG_DEBUG("file_edit: path=" + file_path + " old_len=" + std::to_string(old_string.size()) +
" new_len=" + std::to_string(new_string.size()) +
" replace_all=" + (replace_all ? "true" : "false"));
auto write_guard = MtimeTracker::instance().acquire_write_guard(file_path);
const bool file_exists = std::filesystem::exists(path_from_utf8(file_path));
if (!file_exists && !old_string.empty()) {
return ToolResult{ToolErrors::file_not_found(file_path, current_path_utf8()) +
". Use file_edit with empty old_string or file_write to create a new file.",
false};
}
if (file_exists) {
auto size_check = FileOperations::check_edit_file_size(
file_path,
"Use bounded file_read or grep calls to inspect it. Large-file mutation is not supported.");
if (!size_check.success) {
return size_check;
}
}
TextFileBuffer buffer;
if (file_exists) {
auto read_result = read_text_file_buffer(file_path);
if (!read_result.success) {
auto metadata = MtimeTracker::instance().read_metadata(file_path);
if (metadata && metadata->lossy) {
return ToolResult{ToolErrors::file_read_not_safe_for_edit(file_path), false};
}
return ToolResult{read_result.error, false};
}
buffer = std::move(read_result.buffer);
} else {
buffer.path = file_path;
buffer.metadata = default_new_file_text_metadata();
}
if (old_string.empty()) {
if (file_exists && !is_blank_content(buffer.text)) {
return ToolResult{ToolErrors::cannot_create_file_exists(file_path), false};
}
return run_validated_write(file_path, file_exists, buffer.text,
normalize_text_to_lf(new_string),
buffer.metadata, ctx);
}
const auto read_check = MtimeTracker::instance().validate_read_baseline_for_edit(file_path, buffer.text);
switch (read_check.status) {
case MtimeTracker::ReadBaselineStatus::Ok:
break;
case MtimeTracker::ReadBaselineStatus::NotRead:
return ToolResult{ToolErrors::file_not_read_for_edit(file_path), false};
case MtimeTracker::ReadBaselineStatus::UnsafeRead:
return ToolResult{ToolErrors::file_read_not_safe_for_edit(file_path), false};
case MtimeTracker::ReadBaselineStatus::ExternallyModified:
return ToolResult{ToolErrors::external_modification(file_path), false};
}
std::string normalized_old = normalize_text_to_lf(old_string);
std::string normalized_new = normalize_text_to_lf(new_string);
auto match_plan = build_match_plan(buffer.text, normalized_old, normalized_new);
if (!match_plan.has_value()) {
return make_old_string_not_found_result(file_path, buffer.text, old_string);
}
const size_t count = count_occurrences(buffer.text, match_plan->actual_old);
if (count == 0) {
return make_old_string_not_found_result(file_path, buffer.text, old_string);
}
if (count > 1 && !replace_all) {
return ToolResult{ToolErrors::string_not_unique(count, file_path), false};
}
std::string old_content = buffer.text;
std::string new_content = replace_occurrences(
buffer.text,
match_plan->actual_old,
match_plan->actual_new,
replace_all
);
return run_validated_write(file_path, true, old_content, new_content,
buffer.metadata, ctx);
}
ToolImpl create_file_edit_tool() {
ToolDef def;
def.name = "file_edit";
def.description = "Performs exact string replacements in files. "
"You must use your file_read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. "
"The old_string must appear exactly once unless replace_all is true. "
"Use empty old_string only to create a missing file or fill a blank file. "
"Include surrounding context lines to ensure uniqueness. "
"Existing text files preserve their original encoding and line endings; unsafe encoding changes are rejected. "
"Always use absolute paths, except a supported ACECODE_TMPDIR alias may be the leading component for a temporary file.";
def.parameters = nlohmann::json({
{"type", "object"},
{"properties", {
{"file_path", {
{"type", "string"},
{"description", "Absolute path to the file to edit, or an ACECODE_TMPDIR-prefixed temporary file path"}
}},
{"old_string", {
{"type", "string"},
{"description", "The exact string to find and replace. Empty string creates a missing file or fills a blank file."}
}},
{"new_string", {
{"type", "string"},
{"description", "The replacement string"}
}},
{"replace_all", {
{"type", "boolean"},
{"description", "Replace all occurrences of old_string. Defaults to false."},
{"default", false}
}}
}},
{"required", nlohmann::json::array({"file_path", "old_string", "new_string"})}
});
return ToolImpl{def, execute_file_edit, /*is_read_only=*/false};
}
} // namespace acecode