kovence-cli 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +66 -6
- package/nd.js +22 -1
- package/package.json +1 -1
- package/providers.js +524 -113
- package/src/agent/history.js +502 -9
- package/src/agent/project_context.js +219 -24
- package/src/agent/request_logger.js +148 -0
- package/src/agent/resilience.js +296 -46
- package/src/agent/streaming_write.js +23 -15
- package/src/agent/subagent.js +655 -0
- package/src/agent/turn.js +1210 -269
- package/src/cli/args.js +9 -1
- package/src/cli/sinks.js +188 -106
- package/src/commands/handlers.js +245 -7
- package/src/config/model_registry.js +39 -2
- package/src/config/sessions.js +19 -2
- package/src/config/skills.js +425 -0
- package/src/permissions/engine.js +22 -6
- package/src/permissions/store.js +4 -1
- package/src/settings/schema.js +298 -9
- package/src/settings/store.js +75 -6
- package/src/tools/browser.js +722 -0
- package/src/tools/edit.js +471 -0
- package/src/tools/exec.js +349 -34
- package/src/tools/patch_git.js +12 -1
- package/src/tools/read_tracker.js +87 -0
- package/src/tools/tasks.js +68 -28
- package/tools.js +778 -171
- package/tui.js +142 -30
- package/ui.js +22 -1
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Strip leading line-number prefixes (`12: ` or `12\t`) from target when every non-empty
|
|
5
|
+
* line in target has one and the file itself does not.
|
|
6
|
+
*/
|
|
7
|
+
function stripLineNumberPrefixes(target, fileContent) {
|
|
8
|
+
const tLines = target.split("\n");
|
|
9
|
+
if (tLines.length === 0) return target;
|
|
10
|
+
const prefixRe = /^\s*\d+(?:: |\t)/;
|
|
11
|
+
const nonEmpty = tLines.filter((l) => l.length > 0);
|
|
12
|
+
if (nonEmpty.length === 0) return target;
|
|
13
|
+
if (!nonEmpty.every((l) => prefixRe.test(l))) return target;
|
|
14
|
+
|
|
15
|
+
const fLines = fileContent.split(/\r?\n/).filter((l) => l.length > 0);
|
|
16
|
+
const fileHasPrefixes =
|
|
17
|
+
fLines.length > 0 && fLines.slice(0, Math.min(20, fLines.length)).every((l) => prefixRe.test(l));
|
|
18
|
+
if (fileHasPrefixes) return target;
|
|
19
|
+
|
|
20
|
+
return tLines.map((l) => l.replace(prefixRe, "")).join("\n");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function detectFileFormat(raw) {
|
|
24
|
+
const hasBom = raw.startsWith("\uFEFF");
|
|
25
|
+
const body = hasBom ? raw.slice(1) : raw;
|
|
26
|
+
const crlfCount = (body.match(/\r\n/g) || []).length;
|
|
27
|
+
const lfOnlyCount = (body.match(/(?<!\r)\n/g) || []).length;
|
|
28
|
+
const eol = crlfCount > lfOnlyCount ? "\r\n" : "\n";
|
|
29
|
+
const endsWithNewline = body.endsWith("\n") || body.endsWith("\r\n");
|
|
30
|
+
return { hasBom, body, eol, endsWithNewline };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function restoreFileFormat(lfBody, { hasBom, eol, endsWithNewline }) {
|
|
34
|
+
let out = lfBody.replace(/\r\n/g, "\n");
|
|
35
|
+
if (endsWithNewline && out.length > 0 && !out.endsWith("\n")) {
|
|
36
|
+
out += "\n";
|
|
37
|
+
}
|
|
38
|
+
if (eol === "\r\n") {
|
|
39
|
+
out = out.replace(/\n/g, "\r\n");
|
|
40
|
+
}
|
|
41
|
+
return hasBom ? `\uFEFF${out}` : out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Compute character-offset start/end of every line in an LF string.
|
|
46
|
+
*/
|
|
47
|
+
function indexLines(lfText) {
|
|
48
|
+
const rawLines = lfText.split("\n");
|
|
49
|
+
const lines = [];
|
|
50
|
+
let offset = 0;
|
|
51
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
52
|
+
const text = rawLines[i];
|
|
53
|
+
lines.push({
|
|
54
|
+
lineNum: i + 1,
|
|
55
|
+
text,
|
|
56
|
+
start: offset,
|
|
57
|
+
end: offset + text.length,
|
|
58
|
+
});
|
|
59
|
+
offset += text.length + 1;
|
|
60
|
+
}
|
|
61
|
+
return lines;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function findSpanMatches(lines, targetLines, lineMatcher) {
|
|
65
|
+
const n = targetLines.length;
|
|
66
|
+
if (n === 0 || n > lines.length) return [];
|
|
67
|
+
const matches = [];
|
|
68
|
+
for (let i = 0; i <= lines.length - n; i++) {
|
|
69
|
+
let ok = true;
|
|
70
|
+
for (let j = 0; j < n; j++) {
|
|
71
|
+
if (!lineMatcher(lines[i + j].text, targetLines[j])) {
|
|
72
|
+
ok = false;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (ok) {
|
|
77
|
+
matches.push({
|
|
78
|
+
start: lines[i].start,
|
|
79
|
+
end: lines[i + n - 1].end,
|
|
80
|
+
startLine: lines[i].lineNum,
|
|
81
|
+
endLine: lines[i + n - 1].lineNum,
|
|
82
|
+
contextLine: lines[i].text,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return matches;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function findExactMatches(text, needle) {
|
|
90
|
+
if (!needle) return [];
|
|
91
|
+
const matches = [];
|
|
92
|
+
let pos = 0;
|
|
93
|
+
while (true) {
|
|
94
|
+
const idx = text.indexOf(needle, pos);
|
|
95
|
+
if (idx === -1) break;
|
|
96
|
+
const before = text.slice(0, idx);
|
|
97
|
+
const startLine = before.split("\n").length;
|
|
98
|
+
const lineText = text.split("\n")[startLine - 1] || "";
|
|
99
|
+
matches.push({
|
|
100
|
+
start: idx,
|
|
101
|
+
end: idx + needle.length,
|
|
102
|
+
startLine,
|
|
103
|
+
endLine: startLine + needle.split("\n").length - 1,
|
|
104
|
+
contextLine: lineText,
|
|
105
|
+
});
|
|
106
|
+
pos = idx + needle.length;
|
|
107
|
+
}
|
|
108
|
+
return matches;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function getMinIndent(lines) {
|
|
112
|
+
let minLen = Infinity;
|
|
113
|
+
let minIndentStr = "";
|
|
114
|
+
for (const ln of lines) {
|
|
115
|
+
if (!ln.trim()) continue;
|
|
116
|
+
const m = ln.match(/^([ \t]*)/);
|
|
117
|
+
const ws = m ? m[1] : "";
|
|
118
|
+
if (ws.length < minLen) {
|
|
119
|
+
minLen = ws.length;
|
|
120
|
+
minIndentStr = ws;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return minLen === Infinity ? "" : minIndentStr;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function dedentLines(lines) {
|
|
127
|
+
const base = getMinIndent(lines);
|
|
128
|
+
if (!base) return { dedented: [...lines], baseIndent: "" };
|
|
129
|
+
return {
|
|
130
|
+
baseIndent: base,
|
|
131
|
+
dedented: lines.map((ln) => (ln.trim() ? ln.slice(base.length) : "")),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function reindentReplacement(replacementLf, targetBaseIndent, matchedBaseIndent) {
|
|
136
|
+
const repLines = replacementLf.split("\n");
|
|
137
|
+
return repLines
|
|
138
|
+
.map((ln) => {
|
|
139
|
+
if (!ln.trim()) return "";
|
|
140
|
+
const stripped =
|
|
141
|
+
targetBaseIndent && ln.startsWith(targetBaseIndent) ? ln.slice(targetBaseIndent.length) : ln;
|
|
142
|
+
return `${matchedBaseIndent}${stripped}`;
|
|
143
|
+
})
|
|
144
|
+
.join("\n");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function stringSimilarity(a, b) {
|
|
148
|
+
if (a === b) return 1;
|
|
149
|
+
const lenA = a.length;
|
|
150
|
+
const lenB = b.length;
|
|
151
|
+
if (!lenA && !lenB) return 1;
|
|
152
|
+
if (!lenA || !lenB) return 0;
|
|
153
|
+
|
|
154
|
+
// Bigram Dice coefficient (fast O(N), dependency-free)
|
|
155
|
+
const maxLen = Math.max(lenA, lenB);
|
|
156
|
+
if (lenA < 2 || lenB < 2) {
|
|
157
|
+
return a[0] === b[0] ? 1 / maxLen : 0;
|
|
158
|
+
}
|
|
159
|
+
const bigrams = new Map();
|
|
160
|
+
for (let i = 0; i < lenA - 1; i++) {
|
|
161
|
+
const bg = a.slice(i, i + 2);
|
|
162
|
+
bigrams.set(bg, (bigrams.get(bg) || 0) + 1);
|
|
163
|
+
}
|
|
164
|
+
let overlap = 0;
|
|
165
|
+
for (let i = 0; i < lenB - 1; i++) {
|
|
166
|
+
const bg = b.slice(i, i + 2);
|
|
167
|
+
const cnt = bigrams.get(bg) || 0;
|
|
168
|
+
if (cnt > 0) {
|
|
169
|
+
overlap += 1;
|
|
170
|
+
bigrams.set(bg, cnt - 1);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return (2 * overlap) / (lenA - 1 + (lenB - 1));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function unescapeTargetLiterals(str) {
|
|
177
|
+
return str.replace(/\\(n|r|t|"|'|\\)/g, (_m, ch) => {
|
|
178
|
+
if (ch === "n") return "\n";
|
|
179
|
+
if (ch === "r") return "\r";
|
|
180
|
+
if (ch === "t") return "\t";
|
|
181
|
+
return ch;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function applySpans(text, spans, replacementFn) {
|
|
186
|
+
let out = "";
|
|
187
|
+
let cursor = 0;
|
|
188
|
+
for (const sp of spans) {
|
|
189
|
+
out += text.slice(cursor, sp.start);
|
|
190
|
+
out += replacementFn(sp);
|
|
191
|
+
cursor = sp.end;
|
|
192
|
+
}
|
|
193
|
+
out += text.slice(cursor);
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function findClosestCandidate(lfContent, lfTarget) {
|
|
198
|
+
const fileLines = lfContent.split("\n");
|
|
199
|
+
const targetLines = lfTarget.split("\n");
|
|
200
|
+
const winSize = Math.max(1, targetLines.length);
|
|
201
|
+
if (fileLines.length === 0) return null;
|
|
202
|
+
|
|
203
|
+
let best = null;
|
|
204
|
+
const maxStart = Math.max(0, fileLines.length - winSize);
|
|
205
|
+
for (let i = 0; i <= maxStart; i++) {
|
|
206
|
+
const slice = fileLines.slice(i, i + winSize);
|
|
207
|
+
let simSum = 0;
|
|
208
|
+
let firstDiffOffset = -1;
|
|
209
|
+
for (let j = 0; j < targetLines.length; j++) {
|
|
210
|
+
const fLine = (slice[j] ?? "").trim();
|
|
211
|
+
const tLine = targetLines[j].trim();
|
|
212
|
+
if (fLine !== tLine && firstDiffOffset === -1) {
|
|
213
|
+
firstDiffOffset = j;
|
|
214
|
+
}
|
|
215
|
+
simSum += stringSimilarity(fLine, tLine);
|
|
216
|
+
}
|
|
217
|
+
const score = simSum / targetLines.length;
|
|
218
|
+
if (!best || score > best.score) {
|
|
219
|
+
best = {
|
|
220
|
+
startLine: i + 1,
|
|
221
|
+
endLine: Math.min(fileLines.length, i + winSize),
|
|
222
|
+
score,
|
|
223
|
+
firstDiffLine: firstDiffOffset >= 0 ? i + 1 + firstDiffOffset : i + 1,
|
|
224
|
+
expectedLine: firstDiffOffset >= 0 ? targetLines[firstDiffOffset] : targetLines[0],
|
|
225
|
+
actualLine: firstDiffOffset >= 0 ? (slice[firstDiffOffset] ?? "") : (slice[0] ?? ""),
|
|
226
|
+
preview: slice.slice(0, 6),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return best && best.score >= 0.35 ? best : null;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Generate a compact unified diff (capped at maxDiffLines) between beforeLf and afterLf.
|
|
235
|
+
*/
|
|
236
|
+
function buildShortUnifiedDiff(filePath, beforeRaw, afterRaw, maxDiffLines = 40) {
|
|
237
|
+
const before = beforeRaw.replace(/\r\n/g, "\n").split("\n");
|
|
238
|
+
const after = afterRaw.replace(/\r\n/g, "\n").split("\n");
|
|
239
|
+
let prefix = 0;
|
|
240
|
+
while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) {
|
|
241
|
+
prefix += 1;
|
|
242
|
+
}
|
|
243
|
+
let suffix = 0;
|
|
244
|
+
while (
|
|
245
|
+
suffix < before.length - prefix &&
|
|
246
|
+
suffix < after.length - prefix &&
|
|
247
|
+
before[before.length - 1 - suffix] === after[after.length - 1 - suffix]
|
|
248
|
+
) {
|
|
249
|
+
suffix += 1;
|
|
250
|
+
}
|
|
251
|
+
const ctxStart = Math.max(0, prefix - 2);
|
|
252
|
+
const bEnd = Math.min(before.length, before.length - suffix + 2);
|
|
253
|
+
const aEnd = Math.min(after.length, after.length - suffix + 2);
|
|
254
|
+
const header = [
|
|
255
|
+
`--- a/${filePath}`,
|
|
256
|
+
`+++ b/${filePath}`,
|
|
257
|
+
`@@ -${ctxStart + 1},${bEnd - ctxStart} +${ctxStart + 1},${aEnd - ctxStart} @@`,
|
|
258
|
+
];
|
|
259
|
+
const body = [];
|
|
260
|
+
for (let i = ctxStart; i < prefix; i++) body.push(` ${before[i]}`);
|
|
261
|
+
for (let i = prefix; i < before.length - suffix; i++) body.push(`-${before[i]}`);
|
|
262
|
+
for (let i = prefix; i < after.length - suffix; i++) body.push(`+${after[i]}`);
|
|
263
|
+
for (let i = before.length - suffix; i < bEnd; i++) body.push(` ${before[i]}`);
|
|
264
|
+
|
|
265
|
+
const all = [...header, ...body];
|
|
266
|
+
if (all.length <= maxDiffLines) return all.join("\n");
|
|
267
|
+
return [...all.slice(0, maxDiffLines - 1), `... (${all.length - (maxDiffLines - 1)} more diff lines)`].join("\n");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Apply a single edit using the 7-stage matching pipeline:
|
|
272
|
+
* 1. exact
|
|
273
|
+
* 2. EOL-normalized
|
|
274
|
+
* 3. line-trimmed
|
|
275
|
+
* 4. indentation-flexible
|
|
276
|
+
* 5. whitespace-normalized
|
|
277
|
+
* 6. escape-normalized
|
|
278
|
+
* 7. block anchor (first & last trim equal, middle >= 0.8 similar)
|
|
279
|
+
*/
|
|
280
|
+
function applyFuzzyEdit(rawContent, rawTarget, rawReplacement, { replaceAll = false } = {}) {
|
|
281
|
+
if (typeof rawTarget !== "string" || rawTarget.length === 0) {
|
|
282
|
+
throw new Error("Target cannot be empty when editing an existing file.");
|
|
283
|
+
}
|
|
284
|
+
if (rawTarget === rawReplacement) {
|
|
285
|
+
throw new Error("Target and replacement are identical; no changes to apply.");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const fmt = detectFileFormat(rawContent);
|
|
289
|
+
const cleanedTarget = stripLineNumberPrefixes(rawTarget, fmt.body);
|
|
290
|
+
if (cleanedTarget === rawReplacement) {
|
|
291
|
+
throw new Error("Target and replacement are identical; no changes to apply.");
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const repRaw = String(rawReplacement ?? "");
|
|
295
|
+
|
|
296
|
+
// Stage 1: Exact match against raw file body (after optional BOM)
|
|
297
|
+
const exactMatches = findExactMatches(fmt.body, cleanedTarget);
|
|
298
|
+
if (exactMatches.length > 0) {
|
|
299
|
+
if (exactMatches.length > 1 && !replaceAll) {
|
|
300
|
+
throw buildAmbiguousError(exactMatches);
|
|
301
|
+
}
|
|
302
|
+
const nextBody = applySpans(fmt.body, exactMatches, () => repRaw);
|
|
303
|
+
return {
|
|
304
|
+
content: fmt.hasBom ? `\uFEFF${nextBody}` : nextBody,
|
|
305
|
+
stage: "exact",
|
|
306
|
+
replacements: exactMatches.length,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Work in LF-normalized coordinates for stages 2-7
|
|
311
|
+
const lfContent = fmt.body.replace(/\r\n/g, "\n");
|
|
312
|
+
const lfTarget = cleanedTarget.replace(/\r\n/g, "\n");
|
|
313
|
+
const lfRep = repRaw.replace(/\r\n/g, "\n");
|
|
314
|
+
|
|
315
|
+
const finishLf = (nextLf, stage, count) => ({
|
|
316
|
+
content: restoreFileFormat(nextLf, fmt),
|
|
317
|
+
stage,
|
|
318
|
+
replacements: count,
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// Stage 2: EOL-normalized
|
|
322
|
+
const eolMatches = findExactMatches(lfContent, lfTarget);
|
|
323
|
+
if (eolMatches.length > 0) {
|
|
324
|
+
if (eolMatches.length > 1 && !replaceAll) throw buildAmbiguousError(eolMatches);
|
|
325
|
+
return finishLf(
|
|
326
|
+
applySpans(lfContent, eolMatches, () => lfRep),
|
|
327
|
+
"eol-normalized",
|
|
328
|
+
eolMatches.length
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const fileLines = indexLines(lfContent);
|
|
333
|
+
const targetLines = lfTarget.split("\n");
|
|
334
|
+
|
|
335
|
+
// Stage 3: Indentation-flexible (dedent both sides, re-indent replacement)
|
|
336
|
+
// Run before line-trimmed so uniform indent shifts preserve the file's real indentation.
|
|
337
|
+
const { dedented: dedTargetLines, baseIndent: targetBaseIndent } = dedentLines(targetLines);
|
|
338
|
+
const indentMatches = [];
|
|
339
|
+
for (let i = 0; i <= fileLines.length - targetLines.length; i++) {
|
|
340
|
+
const sliceTexts = fileLines.slice(i, i + targetLines.length).map((l) => l.text);
|
|
341
|
+
const { dedented: dedSliceLines, baseIndent: matchedBaseIndent } = dedentLines(sliceTexts);
|
|
342
|
+
let ok = true;
|
|
343
|
+
for (let j = 0; j < dedTargetLines.length; j++) {
|
|
344
|
+
if (dedSliceLines[j] !== dedTargetLines[j]) {
|
|
345
|
+
ok = false;
|
|
346
|
+
break;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (ok) {
|
|
350
|
+
indentMatches.push({
|
|
351
|
+
start: fileLines[i].start,
|
|
352
|
+
end: fileLines[i + targetLines.length - 1].end,
|
|
353
|
+
startLine: fileLines[i].lineNum,
|
|
354
|
+
endLine: fileLines[i + targetLines.length - 1].lineNum,
|
|
355
|
+
contextLine: fileLines[i].text,
|
|
356
|
+
matchedBaseIndent,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (indentMatches.length > 0) {
|
|
361
|
+
if (indentMatches.length > 1 && !replaceAll) throw buildAmbiguousError(indentMatches);
|
|
362
|
+
const nextLf = applySpans(lfContent, indentMatches, (sp) =>
|
|
363
|
+
reindentReplacement(lfRep, targetBaseIndent, sp.matchedBaseIndent)
|
|
364
|
+
);
|
|
365
|
+
return finishLf(nextLf, "indentation-flexible", indentMatches.length);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Stage 4: Line-trimmed
|
|
369
|
+
const trimMatches = findSpanMatches(fileLines, targetLines, (a, b) => a.trim() === b.trim());
|
|
370
|
+
if (trimMatches.length > 0) {
|
|
371
|
+
if (trimMatches.length > 1 && !replaceAll) throw buildAmbiguousError(trimMatches);
|
|
372
|
+
return finishLf(
|
|
373
|
+
applySpans(lfContent, trimMatches, () => lfRep),
|
|
374
|
+
"line-trimmed",
|
|
375
|
+
trimMatches.length
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Stage 5: Whitespace-normalized (tabs/spaces collapsed per line + trimmed)
|
|
380
|
+
const normWs = (s) => s.replace(/[ \t]+/g, " ").trim();
|
|
381
|
+
const wsMatches = findSpanMatches(fileLines, targetLines, (a, b) => normWs(a) === normWs(b));
|
|
382
|
+
if (wsMatches.length > 0) {
|
|
383
|
+
if (wsMatches.length > 1 && !replaceAll) throw buildAmbiguousError(wsMatches);
|
|
384
|
+
return finishLf(
|
|
385
|
+
applySpans(lfContent, wsMatches, () => lfRep),
|
|
386
|
+
"whitespace-normalized",
|
|
387
|
+
wsMatches.length
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Stage 6: Escape-normalized
|
|
392
|
+
const unescapedTarget = unescapeTargetLiterals(lfTarget);
|
|
393
|
+
if (unescapedTarget !== lfTarget) {
|
|
394
|
+
const escMatches = findExactMatches(lfContent, unescapedTarget);
|
|
395
|
+
if (escMatches.length > 0) {
|
|
396
|
+
if (escMatches.length > 1 && !replaceAll) throw buildAmbiguousError(escMatches);
|
|
397
|
+
const unescapedRep = unescapeTargetLiterals(lfRep);
|
|
398
|
+
return finishLf(
|
|
399
|
+
applySpans(lfContent, escMatches, () => unescapedRep),
|
|
400
|
+
"escape-normalized",
|
|
401
|
+
escMatches.length
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Stage 7: Block anchor (first & last trim equal, middle >= 0.8 similar, single candidate)
|
|
407
|
+
if (targetLines.length >= 3) {
|
|
408
|
+
const firstT = targetLines[0].trim();
|
|
409
|
+
const lastT = targetLines[targetLines.length - 1].trim();
|
|
410
|
+
const blockCandidates = [];
|
|
411
|
+
for (let i = 0; i < fileLines.length; i++) {
|
|
412
|
+
if (fileLines[i].text.trim() !== firstT) continue;
|
|
413
|
+
for (let end = i + 2; end < Math.min(fileLines.length, i + targetLines.length + 10); end++) {
|
|
414
|
+
if (fileLines[end].text.trim() !== lastT) continue;
|
|
415
|
+
const middleFile = fileLines.slice(i + 1, end).map((l) => l.text.trim());
|
|
416
|
+
const middleTarget = targetLines.slice(1, -1).map((l) => l.trim());
|
|
417
|
+
const sim = stringSimilarity(middleFile.join("\n"), middleTarget.join("\n"));
|
|
418
|
+
if (sim >= 0.8) {
|
|
419
|
+
blockCandidates.push({
|
|
420
|
+
start: fileLines[i].start,
|
|
421
|
+
end: fileLines[end].end,
|
|
422
|
+
startLine: fileLines[i].lineNum,
|
|
423
|
+
endLine: fileLines[end].lineNum,
|
|
424
|
+
contextLine: fileLines[i].text,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (blockCandidates.length === 1) {
|
|
430
|
+
return finishLf(
|
|
431
|
+
applySpans(lfContent, blockCandidates, () => lfRep),
|
|
432
|
+
"block-anchor",
|
|
433
|
+
1
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
if (blockCandidates.length > 1) {
|
|
437
|
+
throw buildAmbiguousError(blockCandidates);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// No match found: return actionable closest-candidate diagnostic
|
|
442
|
+
const closest = findClosestCandidate(lfContent, lfTarget);
|
|
443
|
+
if (closest) {
|
|
444
|
+
const pct = Math.round(closest.score * 100);
|
|
445
|
+
throw new Error(
|
|
446
|
+
`Target text not found. Closest candidate (${pct}% match) at lines ${closest.startLine}-${closest.endLine}; ` +
|
|
447
|
+
`first difference at line ${closest.firstDiffLine}:\n` +
|
|
448
|
+
` expected: ${closest.expectedLine}\n` +
|
|
449
|
+
` actual: ${closest.actualLine}`
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
throw new Error("Target text not found in file. Re-read the file with read_file and copy exact lines.");
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function buildAmbiguousError(matches) {
|
|
456
|
+
const locations = matches
|
|
457
|
+
.slice(0, 10)
|
|
458
|
+
.map((m) => ` line ${m.startLine}: ${m.contextLine.trim().slice(0, 80)}`)
|
|
459
|
+
.join("\n");
|
|
460
|
+
const more = matches.length > 10 ? `\n ... (+${matches.length - 10} more)` : "";
|
|
461
|
+
return new Error(
|
|
462
|
+
`Found ${matches.length} occurrences of target.\n${locations}${more}\n` +
|
|
463
|
+
"Provide more surrounding lines to match uniquely, or set replace_all=true."
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
module.exports = {
|
|
468
|
+
stripLineNumberPrefixes,
|
|
469
|
+
applyFuzzyEdit,
|
|
470
|
+
buildShortUnifiedDiff,
|
|
471
|
+
};
|