dsh-awesome-optimizer 2.1.0 → 3.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/README.md +29 -35
- package/README.zh.md +29 -35
- package/cache-diagnostics.md +19 -0
- package/cordis.patch.yml +14 -2
- package/outline-benchmark.md +37 -0
- package/outline-benchmark.windows.json +184 -0
- package/package.json +15 -2
- package/scripts/benchmark-outline.mjs +100 -0
- package/scripts/benchmark.mjs +33 -26
- package/scripts/typecheck.mjs +37 -18
- package/src/ast-outline-config.yml +1 -0
- package/src/ast-outline.js +143 -0
- package/src/cache-diagnostics.js +218 -0
- package/src/code-lexical.js +131 -0
- package/src/code-outline.js +171 -0
- package/src/composite-tools.d.ts +36 -8
- package/src/composite-tools.js +538 -194
- package/src/convergence.js +3 -3
- package/src/custom-prompt.d.ts +7 -1
- package/src/custom-prompt.js +53 -18
- package/src/edit-recovery.d.ts +59 -0
- package/src/edit-recovery.js +524 -0
- package/src/failure-recovery.js +1 -1
- package/src/file-mutation-policy.js +0 -8
- package/src/find-read-output.js +175 -0
- package/src/find-read-ranking.js +63 -0
- package/src/index.d.ts +34 -2
- package/src/index.js +29 -5
- package/src/outline-cache.js +36 -0
- package/src/persistent-eval/daemon-pool.js +3 -2
- package/src/persistent-eval/index.d.ts +35 -8
- package/src/persistent-eval/index.js +51 -16
- package/src/persistent-eval/stdio-runner.js +209 -30
- package/src/persistent-eval/workers/node_worker.mjs +42 -31
- package/src/persistent-eval/workers/py_worker.py +47 -24
- package/src/prompt-linter.js +43 -26
- package/src/read-guard.d.ts +80 -0
- package/src/read-guard.js +336 -0
- package/src/runtime-policy.d.ts +1 -0
- package/src/runtime-policy.js +35 -15
- package/src/telemetry.d.ts +4 -0
- package/src/telemetry.js +27 -8
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import z from '@deepseek-ai/schemastery';
|
|
4
|
+
|
|
5
|
+
export const EditRecoveryConfig = z.object({
|
|
6
|
+
enabled: z.boolean().default(true),
|
|
7
|
+
contextLines: z.number().step(1).min(1).max(30).default(6),
|
|
8
|
+
maxSnippetLines: z.number().step(1).min(5).max(50).default(20),
|
|
9
|
+
maxInspectBytes: z.number().step(1).min(4096).max(4 * 1024 * 1024).default(524288),
|
|
10
|
+
maxHintBytes: z.number().step(1).min(256).max(16384).default(2048),
|
|
11
|
+
maxMultiMatchLocations: z.number().step(1).min(1).max(10).default(3)
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const SKIP_ERROR_CODES = new Set([
|
|
15
|
+
'ABORTED',
|
|
16
|
+
'ABORTED_BEFORE_DISPATCH',
|
|
17
|
+
'APPROVAL_REJECTED',
|
|
18
|
+
'APPROVAL_CANCELLED',
|
|
19
|
+
'APPROVAL_UNAVAILABLE',
|
|
20
|
+
'ENOENT',
|
|
21
|
+
'EACCES',
|
|
22
|
+
'EPERM',
|
|
23
|
+
'EISDIR',
|
|
24
|
+
'INVALID_EDIT_BATCH_ARGS',
|
|
25
|
+
'EDIT_BATCH_LIMIT_EXCEEDED'
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
const DENIAL_OR_MISSING_RE = /(?:\[runtime-policy\]|NO_PROGRESS|ENOENT|EACCES|EPERM|EISDIR|no such file|does not exist on disk|permission denied|sandbox|approval|requires approval|aborted|cancelled|canceled|blocked by)/i;
|
|
29
|
+
const MATCH_FAILURE_RE = /(?:old_string|not found|no match|did not match|does not match|couldn't find|could not find|unable to find|not present|multiple|appears \d+ times|found \d+ match|unique|replace_all|ambiguous|mismatch)/i;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Determine whether an edit error represents a content-matching/uniqueness failure
|
|
33
|
+
* (and NOT a sandbox, permission, missing-file, or policy denial).
|
|
34
|
+
*/
|
|
35
|
+
export function isEditMatchFailure(errorMessage, errorCode) {
|
|
36
|
+
if (errorCode && SKIP_ERROR_CODES.has(errorCode)) return false;
|
|
37
|
+
if (typeof errorMessage !== 'string' || !errorMessage.trim()) return false;
|
|
38
|
+
if (DENIAL_OR_MISSING_RE.test(errorMessage)) return false;
|
|
39
|
+
return MATCH_FAILURE_RE.test(errorMessage);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function splitNormalizedLines(text) {
|
|
43
|
+
return text.split(/\r?\n/);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function normalizeLineText(line) {
|
|
47
|
+
return line.replace(/\s+/g, ' ').trim();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function extractTokens(text) {
|
|
51
|
+
const tokens = text.match(/[A-Za-z0-9_$]+|[\u4e00-\u9fff]+/g);
|
|
52
|
+
if (tokens && tokens.length >= 2) return tokens;
|
|
53
|
+
const compact = text.replace(/\s+/g, '');
|
|
54
|
+
if (compact.length <= 3) return compact ? [compact] : [];
|
|
55
|
+
const shingles = [];
|
|
56
|
+
for (let i = 0; i <= compact.length - 3; i++) {
|
|
57
|
+
shingles.push(compact.slice(i, i + 3));
|
|
58
|
+
}
|
|
59
|
+
return shingles;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function detectIndentStyle(lines) {
|
|
63
|
+
let tabs = 0;
|
|
64
|
+
let spaces = 0;
|
|
65
|
+
for (const line of lines) {
|
|
66
|
+
if (!line.trim()) continue;
|
|
67
|
+
if (line.startsWith('\t')) tabs++;
|
|
68
|
+
else if (/^ {2,}/.test(line)) spaces++;
|
|
69
|
+
}
|
|
70
|
+
if (tabs > spaces * 2 && tabs >= 2) return 'tabs';
|
|
71
|
+
if (spaces > tabs * 2 && spaces >= 2) return 'spaces';
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function findExactOccurrences(content, needle, maxLocations = 3) {
|
|
76
|
+
if (!needle) return { count: 0, locations: [] };
|
|
77
|
+
const locations = [];
|
|
78
|
+
let count = 0;
|
|
79
|
+
let pos = 0;
|
|
80
|
+
let lastLinePos = 0;
|
|
81
|
+
let currentLine = 1;
|
|
82
|
+
|
|
83
|
+
while (true) {
|
|
84
|
+
const idx = content.indexOf(needle, pos);
|
|
85
|
+
if (idx === -1) break;
|
|
86
|
+
count++;
|
|
87
|
+
if (locations.length < maxLocations) {
|
|
88
|
+
for (let i = lastLinePos; i < idx; i++) {
|
|
89
|
+
if (content.charCodeAt(i) === 10) currentLine++;
|
|
90
|
+
}
|
|
91
|
+
lastLinePos = idx;
|
|
92
|
+
const needleLineBreaks = (needle.match(/\n/g) || []).length;
|
|
93
|
+
locations.push({
|
|
94
|
+
startLine: currentLine,
|
|
95
|
+
endLine: currentLine + needleLineBreaks
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
pos = idx + Math.max(1, needle.length);
|
|
99
|
+
}
|
|
100
|
+
return { count, locations };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Locate the best matching region in `content` for a failed `oldString`.
|
|
105
|
+
*/
|
|
106
|
+
export function findBestEditMatch(content, oldString, options = {}) {
|
|
107
|
+
if (typeof content !== 'string' || typeof oldString !== 'string' || !oldString) {
|
|
108
|
+
return { kind: 'no-close-match', totalLines: 0 };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const maxMultiMatchLocations = options.maxMultiMatchLocations ?? 3;
|
|
112
|
+
const exact = findExactOccurrences(content, oldString, maxMultiMatchLocations);
|
|
113
|
+
if (exact.count > 1) {
|
|
114
|
+
return {
|
|
115
|
+
kind: 'multiple-matches',
|
|
116
|
+
count: exact.count,
|
|
117
|
+
locations: exact.locations,
|
|
118
|
+
totalLines: splitNormalizedLines(content).length
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const contentLines = splitNormalizedLines(content);
|
|
123
|
+
const queryLines = splitNormalizedLines(oldString);
|
|
124
|
+
const queryNormLines = queryLines.map(normalizeLineText);
|
|
125
|
+
const nonEmptyQueryLines = queryNormLines
|
|
126
|
+
.map((norm, idx) => ({ norm, idx }))
|
|
127
|
+
.filter(item => item.norm.length > 0);
|
|
128
|
+
|
|
129
|
+
if (nonEmptyQueryLines.length === 0) {
|
|
130
|
+
return { kind: 'no-close-match', totalLines: contentLines.length };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const contentNormLines = contentLines.map(normalizeLineText);
|
|
134
|
+
const fileIndent = detectIndentStyle(contentLines);
|
|
135
|
+
const queryIndent = detectIndentStyle(queryLines);
|
|
136
|
+
const hasCrlfInFile = content.includes('\r\n');
|
|
137
|
+
const hasCrlfInQuery = oldString.includes('\r\n');
|
|
138
|
+
|
|
139
|
+
const indentNotes = [];
|
|
140
|
+
if (fileIndent && queryIndent && fileIndent !== queryIndent) {
|
|
141
|
+
indentNotes.push(`file uses ${fileIndent} indentation whereas old_string uses ${queryIndent}`);
|
|
142
|
+
}
|
|
143
|
+
if (hasCrlfInFile && !hasCrlfInQuery && oldString.includes('\n')) {
|
|
144
|
+
indentNotes.push('file uses CRLF (\\r\\n) line endings');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// 1. Check contiguous line-normalized match (handles indentation / trailing-space drift)
|
|
148
|
+
const qLen = queryNormLines.length;
|
|
149
|
+
for (let start = 0; start <= contentNormLines.length - qLen; start++) {
|
|
150
|
+
let allEqual = true;
|
|
151
|
+
for (let j = 0; j < qLen; j++) {
|
|
152
|
+
if (contentNormLines[start + j] !== queryNormLines[j]) {
|
|
153
|
+
allEqual = false;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (allEqual) {
|
|
158
|
+
return {
|
|
159
|
+
kind: 'whitespace-mismatch',
|
|
160
|
+
startLine: start + 1,
|
|
161
|
+
endLine: start + qLen,
|
|
162
|
+
score: 1,
|
|
163
|
+
notes: indentNotes.length > 0 ? indentNotes : ['whitespace/indentation differs from file'],
|
|
164
|
+
totalLines: contentLines.length
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 2. Anchor-weighted line voting for partially changed multi-line blocks
|
|
170
|
+
const lineIndex = new Map();
|
|
171
|
+
for (let i = 0; i < contentNormLines.length; i++) {
|
|
172
|
+
const norm = contentNormLines[i];
|
|
173
|
+
if (!norm) continue;
|
|
174
|
+
let list = lineIndex.get(norm);
|
|
175
|
+
if (!list) {
|
|
176
|
+
list = [];
|
|
177
|
+
lineIndex.set(norm, list);
|
|
178
|
+
}
|
|
179
|
+
list.push(i);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const candidateScores = new Map();
|
|
183
|
+
let maxPossibleLineWeight = 0;
|
|
184
|
+
for (const { norm, idx: qOffset } of nonEmptyQueryLines) {
|
|
185
|
+
const hits = lineIndex.get(norm);
|
|
186
|
+
const weight = 1 / (1 + (hits ? Math.log2(1 + hits.length) : 0));
|
|
187
|
+
maxPossibleLineWeight += weight;
|
|
188
|
+
if (!hits || hits.length > 64) continue;
|
|
189
|
+
for (const fileIdx of hits) {
|
|
190
|
+
const candidateStart = Math.max(0, fileIdx - qOffset);
|
|
191
|
+
candidateScores.set(candidateStart, (candidateScores.get(candidateStart) ?? 0) + weight);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
let bestStart = -1;
|
|
196
|
+
let bestLineScore = 0;
|
|
197
|
+
for (const [start, score] of candidateScores.entries()) {
|
|
198
|
+
const normalized = maxPossibleLineWeight > 0 ? score / maxPossibleLineWeight : 0;
|
|
199
|
+
if (normalized > bestLineScore) {
|
|
200
|
+
bestLineScore = normalized;
|
|
201
|
+
bestStart = start;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (bestLineScore >= 0.34 && bestStart >= 0) {
|
|
206
|
+
return {
|
|
207
|
+
kind: 'fuzzy-match',
|
|
208
|
+
startLine: bestStart + 1,
|
|
209
|
+
endLine: Math.min(contentLines.length, bestStart + qLen),
|
|
210
|
+
score: bestLineScore,
|
|
211
|
+
notes: indentNotes,
|
|
212
|
+
totalLines: contentLines.length
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 3. Token-rarity sliding window fallback (handles single-line edits or modified identifiers)
|
|
217
|
+
const queryTokens = Array.from(new Set(extractTokens(oldString)));
|
|
218
|
+
if (queryTokens.length === 0) {
|
|
219
|
+
return { kind: 'no-close-match', totalLines: contentLines.length };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const tokenSet = new Set(queryTokens);
|
|
223
|
+
const tokenDocFreq = new Map();
|
|
224
|
+
const lineTokenSets = contentLines.map(line => {
|
|
225
|
+
const lineTokens = extractTokens(line);
|
|
226
|
+
const matched = new Set();
|
|
227
|
+
for (const tok of lineTokens) {
|
|
228
|
+
if (tokenSet.has(tok) && !matched.has(tok)) {
|
|
229
|
+
matched.add(tok);
|
|
230
|
+
tokenDocFreq.set(tok, (tokenDocFreq.get(tok) ?? 0) + 1);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return matched;
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
const tokenWeights = new Map();
|
|
237
|
+
let totalWeight = 0;
|
|
238
|
+
for (const tok of queryTokens) {
|
|
239
|
+
const freq = tokenDocFreq.get(tok) ?? 0;
|
|
240
|
+
const w = freq > 0 ? 1 / Math.log2(2 + freq) : 1;
|
|
241
|
+
tokenWeights.set(tok, w);
|
|
242
|
+
totalWeight += w;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const windowSize = Math.max(1, Math.min(qLen, 12, contentLines.length));
|
|
246
|
+
const activeCounts = new Map();
|
|
247
|
+
let windowScore = 0;
|
|
248
|
+
let bestTokenStart = 0;
|
|
249
|
+
let bestTokenScore = 0;
|
|
250
|
+
|
|
251
|
+
for (let i = 0; i < contentLines.length; i++) {
|
|
252
|
+
for (const tok of lineTokenSets[i]) {
|
|
253
|
+
const prev = activeCounts.get(tok) ?? 0;
|
|
254
|
+
if (prev === 0) windowScore += tokenWeights.get(tok) ?? 0;
|
|
255
|
+
activeCounts.set(tok, prev + 1);
|
|
256
|
+
}
|
|
257
|
+
if (i >= windowSize) {
|
|
258
|
+
const leaving = lineTokenSets[i - windowSize];
|
|
259
|
+
for (const tok of leaving) {
|
|
260
|
+
const nextCount = (activeCounts.get(tok) ?? 1) - 1;
|
|
261
|
+
activeCounts.set(tok, nextCount);
|
|
262
|
+
if (nextCount === 0) windowScore -= tokenWeights.get(tok) ?? 0;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (i >= windowSize - 1) {
|
|
266
|
+
const ratio = totalWeight > 0 ? windowScore / totalWeight : 0;
|
|
267
|
+
if (ratio > bestTokenScore) {
|
|
268
|
+
bestTokenScore = ratio;
|
|
269
|
+
bestTokenStart = i - windowSize + 1;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (bestTokenScore < 0.25) {
|
|
275
|
+
return { kind: 'no-close-match', totalLines: contentLines.length };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return {
|
|
279
|
+
kind: 'fuzzy-match',
|
|
280
|
+
startLine: bestTokenStart + 1,
|
|
281
|
+
endLine: Math.min(contentLines.length, bestTokenStart + windowSize),
|
|
282
|
+
score: bestTokenScore,
|
|
283
|
+
notes: indentNotes,
|
|
284
|
+
totalLines: contentLines.length
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function formatNumberedWindow(lines, startLine, endLine, maxLineChars = 240) {
|
|
289
|
+
const from = Math.max(1, startLine);
|
|
290
|
+
const to = Math.min(lines.length, endLine);
|
|
291
|
+
const width = String(to).length;
|
|
292
|
+
const out = [];
|
|
293
|
+
for (let lineNo = from; lineNo <= to; lineNo++) {
|
|
294
|
+
const raw = lines[lineNo - 1].replace(/\r$/, '');
|
|
295
|
+
const clipped = raw.length > maxLineChars
|
|
296
|
+
? `${raw.slice(0, maxLineChars)}... [+${raw.length - maxLineChars} chars]`
|
|
297
|
+
: raw;
|
|
298
|
+
out.push(`${String(lineNo).padStart(width, ' ')} | ${clipped}`);
|
|
299
|
+
}
|
|
300
|
+
return out.join('\n');
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function clampWindowToLineBudget(startLine, endLine, totalLines, contextLines, maxSnippetLines) {
|
|
304
|
+
let from = Math.max(1, startLine - contextLines);
|
|
305
|
+
let to = Math.min(totalLines, endLine + contextLines);
|
|
306
|
+
if (to - from + 1 <= maxSnippetLines) {
|
|
307
|
+
return { from, to };
|
|
308
|
+
}
|
|
309
|
+
const spanLen = endLine - startLine + 1;
|
|
310
|
+
if (spanLen >= maxSnippetLines) {
|
|
311
|
+
return { from: startLine, to: Math.min(totalLines, startLine + maxSnippetLines - 1) };
|
|
312
|
+
}
|
|
313
|
+
const extra = maxSnippetLines - spanLen;
|
|
314
|
+
const before = Math.floor(extra / 2);
|
|
315
|
+
from = Math.max(1, startLine - before);
|
|
316
|
+
to = Math.min(totalLines, from + maxSnippetLines - 1);
|
|
317
|
+
if (to - from + 1 < maxSnippetLines) {
|
|
318
|
+
from = Math.max(1, to - maxSnippetLines + 1);
|
|
319
|
+
}
|
|
320
|
+
return { from, to };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function trimToMaxBytes(text, maxBytes) {
|
|
324
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text;
|
|
325
|
+
const lines = text.split('\n');
|
|
326
|
+
while (lines.length > 3 && Buffer.byteLength(lines.join('\n'), 'utf8') > maxBytes) {
|
|
327
|
+
lines.pop();
|
|
328
|
+
}
|
|
329
|
+
return `${lines.join('\n')}\n... [context truncated at ${maxBytes} bytes]`;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Build a concise, line-numbered recovery hint for a failed edit on `content`.
|
|
334
|
+
*/
|
|
335
|
+
export function buildEditFailureHint(content, oldString, options = {}) {
|
|
336
|
+
const contextLines = options.contextLines ?? 6;
|
|
337
|
+
const maxSnippetLines = options.maxSnippetLines ?? 20;
|
|
338
|
+
const maxHintBytes = options.maxHintBytes ?? 2048;
|
|
339
|
+
const maxMultiMatchLocations = options.maxMultiMatchLocations ?? 3;
|
|
340
|
+
const filePath = options.filePath || 'target file';
|
|
341
|
+
|
|
342
|
+
const match = findBestEditMatch(content, oldString, { maxMultiMatchLocations });
|
|
343
|
+
const lines = splitNormalizedLines(content);
|
|
344
|
+
|
|
345
|
+
if (match.kind === 'multiple-matches') {
|
|
346
|
+
const locSummary = match.locations
|
|
347
|
+
.map(loc => (loc.startLine === loc.endLine ? `${loc.startLine}` : `${loc.startLine}-${loc.endLine}`))
|
|
348
|
+
.join(', ');
|
|
349
|
+
const moreSuffix = match.count > match.locations.length ? `, ... (${match.count} total)` : '';
|
|
350
|
+
const snippets = match.locations.map((loc, idx) => {
|
|
351
|
+
const from = Math.max(1, loc.startLine - 1);
|
|
352
|
+
const to = Math.min(lines.length, loc.endLine + 1);
|
|
353
|
+
return `Match #${idx + 1} (lines ${from}-${to}):\n${formatNumberedWindow(lines, from, to)}`;
|
|
354
|
+
});
|
|
355
|
+
const text = [
|
|
356
|
+
`[edit-recovery] '${filePath}' contains ${match.count} exact matches (lines ${locSummary}${moreSuffix}). Pass replace_all=true or include surrounding lines to target one uniquely:`,
|
|
357
|
+
...snippets
|
|
358
|
+
].join('\n');
|
|
359
|
+
return trimToMaxBytes(text, maxHintBytes);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (match.kind === 'no-close-match') {
|
|
363
|
+
return `[edit-recovery] No close match for old_string in '${filePath}' (${match.totalLines} lines). Re-read the target region before retrying.`;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const { from, to } = clampWindowToLineBudget(
|
|
367
|
+
match.startLine,
|
|
368
|
+
match.endLine,
|
|
369
|
+
lines.length,
|
|
370
|
+
contextLines,
|
|
371
|
+
maxSnippetLines
|
|
372
|
+
);
|
|
373
|
+
|
|
374
|
+
const label = match.kind === 'whitespace-mismatch'
|
|
375
|
+
? `Exact match after whitespace/indentation normalization at lines ${match.startLine}-${match.endLine}`
|
|
376
|
+
: `Closest match near lines ${match.startLine}-${match.endLine}`;
|
|
377
|
+
const noteText = match.notes?.length ? ` (${match.notes.join('; ')})` : '';
|
|
378
|
+
const hint = [
|
|
379
|
+
`[edit-recovery] ${label} in '${filePath}'${noteText}. Copy exact lines ${from}-${to} below:`,
|
|
380
|
+
formatNumberedWindow(lines, from, to)
|
|
381
|
+
].join('\n');
|
|
382
|
+
return trimToMaxBytes(hint, maxHintBytes);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function readTargetForRecovery(filePath, cwd, fsService, signal, maxInspectBytes) {
|
|
386
|
+
if (!filePath || typeof filePath !== 'string') return null;
|
|
387
|
+
|
|
388
|
+
if (fsService) {
|
|
389
|
+
if (typeof fsService.readFile === 'function') {
|
|
390
|
+
try {
|
|
391
|
+
const content = await fsService.readFile(filePath, { cwd, signal, encoding: 'utf8' });
|
|
392
|
+
if (typeof content !== 'string') return null;
|
|
393
|
+
return Buffer.byteLength(content, 'utf8') <= maxInspectBytes ? content : null;
|
|
394
|
+
} catch {
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (typeof fsService.readText === 'function') {
|
|
399
|
+
try {
|
|
400
|
+
const target = typeof fsService.resolve === 'function'
|
|
401
|
+
? await fsService.resolve(filePath, { cwd, signal })
|
|
402
|
+
: filePath;
|
|
403
|
+
const content = await fsService.readText(target, signal);
|
|
404
|
+
if (typeof content !== 'string') return null;
|
|
405
|
+
return Buffer.byteLength(content, 'utf8') <= maxInspectBytes ? content : null;
|
|
406
|
+
} catch {
|
|
407
|
+
// Fall through to disk
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(cwd || process.cwd(), filePath);
|
|
414
|
+
const stat = await fs.stat(resolved);
|
|
415
|
+
if (!stat.isFile() || stat.size > maxInspectBytes) return null;
|
|
416
|
+
return await fs.readFile(resolved, 'utf8');
|
|
417
|
+
} catch {
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Mount `tools/post-execute` enrichment so failed `edit` (and `edit_batch` sub-call)
|
|
424
|
+
* invocations automatically return numbered nearby context without an extra `read` turn.
|
|
425
|
+
*/
|
|
426
|
+
export function applyEditRecovery(ctx, rawConfig = {}) {
|
|
427
|
+
const config = EditRecoveryConfig(rawConfig);
|
|
428
|
+
if (!config.enabled) return null;
|
|
429
|
+
|
|
430
|
+
const statsBySession = new WeakMap();
|
|
431
|
+
const statsFor = session => {
|
|
432
|
+
if (!session) return null;
|
|
433
|
+
let s = statsBySession.get(session);
|
|
434
|
+
if (!s) {
|
|
435
|
+
s = { inspected: 0, hintsAttached: 0, skipped: 0 };
|
|
436
|
+
statsBySession.set(session, s);
|
|
437
|
+
}
|
|
438
|
+
return s;
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
ctx.on('session/event', (session, event) => {
|
|
442
|
+
if (event?.type === 'turn/start') {
|
|
443
|
+
statsBySession.set(session, { inspected: 0, hintsAttached: 0, skipped: 0 });
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
ctx.on('tools/post-execute', async (exec, result, next) => {
|
|
448
|
+
const decision = await next();
|
|
449
|
+
if (exec?.name !== 'edit' || !result?.isError || exec.signal?.aborted) {
|
|
450
|
+
return decision;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const args = exec.arguments;
|
|
454
|
+
if (!args || typeof args.file_path !== 'string' || typeof args.old_string !== 'string' || !args.old_string) {
|
|
455
|
+
return decision;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const decisionText = decision?.kind === 'block'
|
|
459
|
+
? (decision.feedback ?? []).filter(b => b.type === 'text').map(b => b.text).join('\n')
|
|
460
|
+
: null;
|
|
461
|
+
const baseMessage = decisionText
|
|
462
|
+
|| result.error?.message
|
|
463
|
+
|| result.content?.filter(b => b.type === 'text').map(b => b.text).join('\n')
|
|
464
|
+
|| '';
|
|
465
|
+
const errorCode = decision?.kind === 'block' ? (decision.info?.code ?? result.error?.info?.code) : result.error?.info?.code;
|
|
466
|
+
const session = exec.agent?.session;
|
|
467
|
+
const stats = statsFor(session);
|
|
468
|
+
if (!isEditMatchFailure(baseMessage, errorCode)) {
|
|
469
|
+
if (stats) stats.skipped++;
|
|
470
|
+
return decision;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
if (stats) stats.inspected++;
|
|
474
|
+
|
|
475
|
+
const fsService = ctx.get ? ctx.get('fs') : undefined;
|
|
476
|
+
const cwdService = ctx.get ? ctx.get('workingDirectory') : undefined;
|
|
477
|
+
const cwd = cwdService?.get?.(session) ?? '';
|
|
478
|
+
|
|
479
|
+
const content = await readTargetForRecovery(
|
|
480
|
+
args.file_path,
|
|
481
|
+
cwd,
|
|
482
|
+
fsService,
|
|
483
|
+
exec.signal,
|
|
484
|
+
config.maxInspectBytes
|
|
485
|
+
);
|
|
486
|
+
if (content === null || exec.signal?.aborted) {
|
|
487
|
+
if (stats) stats.skipped++;
|
|
488
|
+
return decision;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const hint = buildEditFailureHint(content, args.old_string, {
|
|
492
|
+
filePath: args.file_path,
|
|
493
|
+
contextLines: config.contextLines,
|
|
494
|
+
maxSnippetLines: config.maxSnippetLines,
|
|
495
|
+
maxHintBytes: config.maxHintBytes,
|
|
496
|
+
maxMultiMatchLocations: config.maxMultiMatchLocations
|
|
497
|
+
});
|
|
498
|
+
if (!hint) return decision;
|
|
499
|
+
|
|
500
|
+
if (stats) stats.hintsAttached++;
|
|
501
|
+
const enriched = baseMessage ? `${baseMessage}\n\n${hint}` : hint;
|
|
502
|
+
return {
|
|
503
|
+
kind: 'block',
|
|
504
|
+
feedback: [{ type: 'text', text: enriched }],
|
|
505
|
+
...(result.error?.info ? { info: result.error.info } : {})
|
|
506
|
+
};
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
return {
|
|
510
|
+
getStats(session) {
|
|
511
|
+
const s = session ? statsBySession.get(session) : null;
|
|
512
|
+
return s ? { ...s } : { inspected: 0, hintsAttached: 0, skipped: 0 };
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export const name = 'agent-optimizer-edit-recovery';
|
|
518
|
+
export const inject = ['tools'];
|
|
519
|
+
export const Config = EditRecoveryConfig;
|
|
520
|
+
export function apply(ctx, config = {}) {
|
|
521
|
+
const service = applyEditRecovery(ctx, config);
|
|
522
|
+
if (service) ctx.provide('editRecovery', service);
|
|
523
|
+
}
|
|
524
|
+
export default { name, inject, Config, apply };
|
package/src/failure-recovery.js
CHANGED
|
@@ -9,7 +9,7 @@ export const RETRY_TOOL = 'retry_failed_write';
|
|
|
9
9
|
export const PAIRING_ERROR = 'invalid escalation: justification is only valid together with sandbox_permissions';
|
|
10
10
|
const MIN_BYTES = 8 * 1024;
|
|
11
11
|
const MAX_BYTES = 1024 * 1024;
|
|
12
|
-
const READ_ONLY = new Set(['read', 'read_image', '
|
|
12
|
+
const READ_ONLY = new Set(['read', 'read_image', 'find_and_read', 'glob', 'grep', 'skill', 'eval_python', 'eval_node']);
|
|
13
13
|
|
|
14
14
|
export const FailureRecoveryConfig = z.object({
|
|
15
15
|
enabled: z.boolean().default(true),
|
|
@@ -204,14 +204,6 @@ export class FileMutationPolicyManager {
|
|
|
204
204
|
state.observedFiles.add(filePath);
|
|
205
205
|
state.knownExistingFiles.add(filePath);
|
|
206
206
|
}
|
|
207
|
-
} else if (exec.name === 'read_batch' && Array.isArray(args.files)) {
|
|
208
|
-
for (const item of args.files) {
|
|
209
|
-
if (typeof item?.file_path === 'string') {
|
|
210
|
-
const filePath = normalizePath(item.file_path, state.cwd);
|
|
211
|
-
state.observedFiles.add(filePath);
|
|
212
|
-
state.knownExistingFiles.add(filePath);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
207
|
} else if (['grep', 'glob'].includes(exec.name)) {
|
|
216
208
|
if (typeof args.path === 'string') {
|
|
217
209
|
state.observedFiles.add(normalizePath(args.path, state.cwd));
|