@burtson-labs/agent-core 1.6.99 → 1.6.100
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/dist/mcp/toolAdapter.d.ts +7 -0
- package/dist/mcp/toolAdapter.d.ts.map +1 -1
- package/dist/mcp/toolAdapter.js +12 -1
- package/dist/mcp/toolAdapter.js.map +1 -1
- package/dist/security/secretPatterns.d.ts +7 -0
- package/dist/security/secretPatterns.d.ts.map +1 -1
- package/dist/security/secretPatterns.js +104 -0
- package/dist/security/secretPatterns.js.map +1 -1
- package/dist/tools/core-tools.d.ts +14 -0
- package/dist/tools/core-tools.d.ts.map +1 -1
- package/dist/tools/core-tools.js +350 -223
- package/dist/tools/core-tools.js.map +1 -1
- package/dist/tools/tool-use-parser.d.ts +1 -0
- package/dist/tools/tool-use-parser.d.ts.map +1 -1
- package/dist/tools/tool-use-parser.js +29 -3
- package/dist/tools/tool-use-parser.js.map +1 -1
- package/dist/tools/unified-patch.d.ts +14 -5
- package/dist/tools/unified-patch.d.ts.map +1 -1
- package/dist/tools/unified-patch.js +28 -5
- package/dist/tools/unified-patch.js.map +1 -1
- package/package.json +1 -1
package/dist/tools/core-tools.js
CHANGED
|
@@ -10,6 +10,7 @@ exports.createSkillTool = exports.watchCommandTool = exports.runCommandTool = ex
|
|
|
10
10
|
exports.decodeOverEscaped = decodeOverEscaped;
|
|
11
11
|
exports.addFileLines = addFileLines;
|
|
12
12
|
exports.resolvePatchHunk = resolvePatchHunk;
|
|
13
|
+
exports.reindentToFile = reindentToFile;
|
|
13
14
|
exports.workspaceDisplayPath = workspaceDisplayPath;
|
|
14
15
|
exports.noMatchHint = noMatchHint;
|
|
15
16
|
exports.runCommandRefusal = runCommandRefusal;
|
|
@@ -1141,9 +1142,197 @@ function resolvePatchHunk(hunk, file) {
|
|
|
1141
1142
|
}
|
|
1142
1143
|
return { ...oneChar, occurrences: oneCharCount, spelling: 'one-char' };
|
|
1143
1144
|
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Write every staged file, or none. When a write fails part-way, files
|
|
1147
|
+
* already written are put back (original content restored, files the
|
|
1148
|
+
* patch created removed) so a disk error cannot leave half a patch behind.
|
|
1149
|
+
*/
|
|
1150
|
+
async function commitStagedFiles(staged, ctx) {
|
|
1151
|
+
const done = [];
|
|
1152
|
+
const blanked = new Set();
|
|
1153
|
+
const rel = (p) => (p.startsWith(`${ctx.workspaceRoot}/`) ? p.slice(ctx.workspaceRoot.length + 1) : p);
|
|
1154
|
+
for (const [absPath, file] of staged) {
|
|
1155
|
+
try {
|
|
1156
|
+
if (file.content === null) {
|
|
1157
|
+
if (file.original === null) {
|
|
1158
|
+
continue;
|
|
1159
|
+
} // added then deleted in the same patch
|
|
1160
|
+
if (typeof ctx.deleteFile === 'function') {
|
|
1161
|
+
await ctx.deleteFile(absPath);
|
|
1162
|
+
}
|
|
1163
|
+
else {
|
|
1164
|
+
await ctx.writeFile(absPath, '');
|
|
1165
|
+
blanked.add(absPath);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
else {
|
|
1169
|
+
await ctx.writeFile(absPath, (0, unified_patch_1.withLineEnding)(file.content, file.eol));
|
|
1170
|
+
}
|
|
1171
|
+
done.push([absPath, file]);
|
|
1172
|
+
}
|
|
1173
|
+
catch (err) {
|
|
1174
|
+
const verb = file.content === null ? 'Delete' : file.original === null ? 'Add' : 'Update';
|
|
1175
|
+
const failure = `${verb} ${rel(absPath)}: ${err instanceof Error ? err.message : String(err)}`;
|
|
1176
|
+
const unrestored = [];
|
|
1177
|
+
for (const [donePath, doneFile] of done.reverse()) {
|
|
1178
|
+
try {
|
|
1179
|
+
if (doneFile.original !== null) {
|
|
1180
|
+
await ctx.writeFile(donePath, doneFile.original);
|
|
1181
|
+
}
|
|
1182
|
+
else if (typeof ctx.deleteFile === 'function') {
|
|
1183
|
+
await ctx.deleteFile(donePath);
|
|
1184
|
+
}
|
|
1185
|
+
else {
|
|
1186
|
+
unrestored.push(rel(donePath));
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
catch {
|
|
1190
|
+
unrestored.push(rel(donePath));
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
const rollbackNote = done.length === 0
|
|
1194
|
+
? 'Nothing was written.'
|
|
1195
|
+
: unrestored.length === 0
|
|
1196
|
+
? `The ${done.length} file${done.length === 1 ? '' : 's'} written before the failure ${done.length === 1 ? 'was' : 'were'} restored; nothing changed.`
|
|
1197
|
+
: `Could not restore: ${unrestored.join(', ')} — check ${unrestored.length === 1 ? 'it' : 'them'} with read_file before retrying.`;
|
|
1198
|
+
return { ok: false, failure, rollbackNote };
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
return { ok: true, blanked };
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Re-indent a replacement to the file's real indentation after a
|
|
1205
|
+
* whitespace-tolerant match.
|
|
1206
|
+
*
|
|
1207
|
+
* The fallback match ignores indentation width, so a hunk written at four
|
|
1208
|
+
* spaces matches a block that sits at eight (or at a tab). Splicing the
|
|
1209
|
+
* replacement as written then moved the block to the patch's indentation —
|
|
1210
|
+
* harmless in a brace language, a syntax or scoping change in Python or
|
|
1211
|
+
* YAML. When the matched file lines and the patch's find lines differ by a
|
|
1212
|
+
* consistent leading prefix (file = A + rest wherever patch = B + rest),
|
|
1213
|
+
* apply the same A-for-B swap to every replacement line that starts with B.
|
|
1214
|
+
* If the relation is not consistent, the replacement is left as written.
|
|
1215
|
+
*/
|
|
1216
|
+
function reindentToFile(findLines, fileLines, replace) {
|
|
1217
|
+
const ws = (l) => /^[ \t]*/.exec(l)?.[0] ?? '';
|
|
1218
|
+
const pairs = findLines
|
|
1219
|
+
.map((l, i) => [l, fileLines[i] ?? ''])
|
|
1220
|
+
.filter(([l, f]) => l.trim().length > 0 && f.trim().length > 0);
|
|
1221
|
+
if (pairs.length === 0) {
|
|
1222
|
+
return replace;
|
|
1223
|
+
}
|
|
1224
|
+
let base = pairs[0];
|
|
1225
|
+
for (const p of pairs) {
|
|
1226
|
+
if (ws(p[0]).length < ws(base[0]).length) {
|
|
1227
|
+
base = p;
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
const fromPrefix = ws(base[0]);
|
|
1231
|
+
const toPrefix = ws(base[1]);
|
|
1232
|
+
if (fromPrefix === toPrefix) {
|
|
1233
|
+
return replace;
|
|
1234
|
+
}
|
|
1235
|
+
const consistent = pairs.every(([l, f]) => {
|
|
1236
|
+
const li = ws(l);
|
|
1237
|
+
const fi = ws(f);
|
|
1238
|
+
return li.startsWith(fromPrefix) && fi.startsWith(toPrefix) && li.slice(fromPrefix.length) === fi.slice(toPrefix.length);
|
|
1239
|
+
});
|
|
1240
|
+
if (!consistent) {
|
|
1241
|
+
return replace;
|
|
1242
|
+
}
|
|
1243
|
+
return replace
|
|
1244
|
+
.split('\n')
|
|
1245
|
+
.map((l) => (l.trim().length > 0 && l.startsWith(fromPrefix) ? toPrefix + l.slice(fromPrefix.length) : l))
|
|
1246
|
+
.join('\n');
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Apply an envelope Update block's hunks to `before`, in order. Every hunk
|
|
1250
|
+
* is tried (so the failure report names all of them), but the caller only
|
|
1251
|
+
* uses `after` when `failed` is empty.
|
|
1252
|
+
*/
|
|
1253
|
+
function applyEnvelopeHunks(before, hunks) {
|
|
1254
|
+
let after = before;
|
|
1255
|
+
const failed = [];
|
|
1256
|
+
for (let hi = 0; hi < hunks.length; hi++) {
|
|
1257
|
+
const hunk = hunks[hi];
|
|
1258
|
+
const contextCount = hunk.filter((item) => item.kind === 'context').length;
|
|
1259
|
+
const resolved = resolvePatchHunk(hunk, after);
|
|
1260
|
+
const { find, occurrences } = resolved;
|
|
1261
|
+
let { replace } = resolved;
|
|
1262
|
+
if (!find) {
|
|
1263
|
+
failed.push(`hunk #${hi + 1}: empty (no removed lines and no context)`);
|
|
1264
|
+
continue;
|
|
1265
|
+
}
|
|
1266
|
+
if (occurrences === 1) {
|
|
1267
|
+
// Function replacer: a string one would expand `$&`, `$$`, `$1` in the patch text.
|
|
1268
|
+
after = after.replace(find, () => replace);
|
|
1269
|
+
continue;
|
|
1270
|
+
}
|
|
1271
|
+
if (occurrences > 1) {
|
|
1272
|
+
failed.push(`hunk #${hi + 1}: matches ${occurrences} places — add more context to make it unique`);
|
|
1273
|
+
continue;
|
|
1274
|
+
}
|
|
1275
|
+
// occurrences === 0: whitespace-tolerant fallback. Collapse every run
|
|
1276
|
+
// of whitespace within a line to a single space (newlines kept as line
|
|
1277
|
+
// separators) on BOTH sides; a unique match is mapped back to its line
|
|
1278
|
+
// range in the file and spliced. Catches indentation drift and
|
|
1279
|
+
// trailing-whitespace differences without giving up multi-match safety.
|
|
1280
|
+
const normalize = (s) => s.split('\n').map((l) => l.replace(/[ \t]+/g, ' ').trimEnd()).join('\n');
|
|
1281
|
+
const normalizedFind = normalize(find);
|
|
1282
|
+
const normalOccurrences = normalize(after).split(normalizedFind).length - 1;
|
|
1283
|
+
if (normalOccurrences === 1) {
|
|
1284
|
+
const afterLines = after.split('\n');
|
|
1285
|
+
const findWindow = find.split('\n');
|
|
1286
|
+
const findLineCount = findWindow.length;
|
|
1287
|
+
let matchedStart = -1;
|
|
1288
|
+
for (let i = 0; i + findLineCount <= afterLines.length; i++) {
|
|
1289
|
+
if (normalize(afterLines.slice(i, i + findLineCount).join('\n')) === normalizedFind) {
|
|
1290
|
+
matchedStart = i;
|
|
1291
|
+
break;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
if (matchedStart >= 0) {
|
|
1295
|
+
const fileWindow = afterLines.slice(matchedStart, matchedStart + findLineCount);
|
|
1296
|
+
let offByOne = false;
|
|
1297
|
+
// A whitespace-tolerant match says nothing about the marker
|
|
1298
|
+
// spelling. When every matched file line is indented exactly
|
|
1299
|
+
// one space less than the patch's line, the model wrote
|
|
1300
|
+
// "marker + space": drop that space from the added lines too.
|
|
1301
|
+
if (resolved.spelling === 'one-char') {
|
|
1302
|
+
// Removed lines only: context lines may be spelled either way.
|
|
1303
|
+
const findKinds = hunk.filter((item) => item.kind !== 'added').map((item) => item.kind);
|
|
1304
|
+
const pairs = findWindow
|
|
1305
|
+
.map((l, i) => [l, fileWindow[i] ?? '', findKinds[i]])
|
|
1306
|
+
.filter(([l, , kind]) => kind === 'removed' && l.trim().length > 0);
|
|
1307
|
+
offByOne = pairs.length > 0 &&
|
|
1308
|
+
pairs.every(([l, f]) => leadingSpaces(l) === leadingSpaces(f) + 1 && !/^\s*\t/.test(f));
|
|
1309
|
+
if (offByOne) {
|
|
1310
|
+
replace = hunk
|
|
1311
|
+
.filter((item) => item.kind !== 'removed')
|
|
1312
|
+
.map((item) => (item.kind === 'added' ? dropMarkerSpace(item.text) : item.text))
|
|
1313
|
+
.join('\n');
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
if (!offByOne) {
|
|
1317
|
+
replace = reindentToFile(findWindow, fileWindow, replace);
|
|
1318
|
+
}
|
|
1319
|
+
after = [
|
|
1320
|
+
...afterLines.slice(0, matchedStart),
|
|
1321
|
+
...replace.split('\n'),
|
|
1322
|
+
...afterLines.slice(matchedStart + findLineCount)
|
|
1323
|
+
].join('\n');
|
|
1324
|
+
continue;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
const preview = find.length > 160 ? find.slice(0, 160) + '…' : find;
|
|
1328
|
+
failed.push(`hunk #${hi + 1}: text not found (${contextCount} context line${contextCount === 1 ? '' : 's'} provided). ` +
|
|
1329
|
+
`Tried to find:\n${preview.split('\n').map((l) => ` ${l}`).join('\n')}`);
|
|
1330
|
+
}
|
|
1331
|
+
return { after, failed };
|
|
1332
|
+
}
|
|
1144
1333
|
const applyPatchTool = {
|
|
1145
1334
|
name: 'apply_patch',
|
|
1146
|
-
description: 'Apply a multi-file patch in a single tool call. Use this when you have to change 2+ files (rename, refactor, multi-method comment pass) — much cheaper than calling apply_edit N times. Two accepted formats: (1) **standard unified diff** — what `git diff` produces, with `--- a/path`, `+++ b/path`, `@@` hunks, ` `/`-`/`+` body lines. Most models emit this format natively. Single-file unified diffs accepted; for multi-file, concatenate diffs with their own headers. (2) **Codex envelope** — `*** Begin Patch` / `*** End Patch` wrapping `*** Update File: <path>` / `*** Add File:` / `*** Delete File:` blocks. The tool auto-detects the format from the input.',
|
|
1335
|
+
description: 'Apply a multi-file patch in a single tool call. Use this when you have to change 2+ files (rename, refactor, multi-method comment pass) — much cheaper than calling apply_edit N times. Two accepted formats: (1) **standard unified diff** — what `git diff` produces, with `--- a/path`, `+++ b/path`, `@@` hunks, ` `/`-`/`+` body lines. Most models emit this format natively. Single-file unified diffs accepted; for multi-file, concatenate diffs with their own headers. (2) **Codex envelope** — `*** Begin Patch` / `*** End Patch` wrapping `*** Update File: <path>` / `*** Add File:` / `*** Delete File:` blocks. The tool auto-detects the format from the input. All-or-nothing: if any hunk fails, no file is written and the error names the failing hunks.',
|
|
1147
1336
|
parameters: [
|
|
1148
1337
|
{ name: 'patch', description: 'The full patch — either a unified diff (starts with `--- ` / `+++ ` / `@@`) or a `*** Begin Patch` envelope. For unified diffs the path is read from the `+++ b/<path>` header; for the envelope each `*** Update File:` block names its own path.', required: true },
|
|
1149
1338
|
{ name: 'path', description: 'Optional explicit path. When set with a unified diff, overrides whatever the `+++ b/...` header says — useful when the model emits a diff without proper headers.', required: false }
|
|
@@ -1262,202 +1451,121 @@ const applyPatchTool = {
|
|
|
1262
1451
|
if (actions.length === 0) {
|
|
1263
1452
|
return { output: 'apply_patch rejected: envelope contained no action blocks. Use `*** Update File:`, `*** Add File:`, or `*** Delete File:` headers.', isError: true };
|
|
1264
1453
|
}
|
|
1265
|
-
//
|
|
1266
|
-
//
|
|
1267
|
-
//
|
|
1268
|
-
|
|
1454
|
+
// Atomic: stage every action against an in-memory view of the files
|
|
1455
|
+
// first, and write only when every action staged cleanly. A failure
|
|
1456
|
+
// anywhere writes nothing and returns isError:true naming the action
|
|
1457
|
+
// and hunk.
|
|
1458
|
+
//
|
|
1459
|
+
// This replaced per-action / per-hunk partial application (v1.7.298),
|
|
1460
|
+
// which wrote the files whose hunks matched, skipped the rest and
|
|
1461
|
+
// returned isError:false with "Partially updated". A rename or
|
|
1462
|
+
// refactor applied half-way leaves the tree in a state neither the
|
|
1463
|
+
// model nor the user asked for (a renamed definition with stale call
|
|
1464
|
+
// sites), and isError:false let the model carry on as if it had
|
|
1465
|
+
// landed. The failure notes still name each failing hunk with what was
|
|
1466
|
+
// searched for, so the retry only has to fix those hunks — but it
|
|
1467
|
+
// re-sends the whole patch, against files that are still as it read
|
|
1468
|
+
// them.
|
|
1469
|
+
const staged = new Map();
|
|
1470
|
+
const pending = [];
|
|
1471
|
+
const failures = [];
|
|
1269
1472
|
for (const action of actions) {
|
|
1270
1473
|
const absPath = isAbsolutePath(action.path)
|
|
1271
1474
|
? action.path
|
|
1272
1475
|
: `${ctx.workspaceRoot}/${action.path}`;
|
|
1476
|
+
const prior = staged.get(absPath);
|
|
1273
1477
|
if (action.kind === 'delete') {
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
// — Bandit's own self-eval flagged this as a real footgun.
|
|
1282
|
-
if (typeof ctx.deleteFile === 'function') {
|
|
1283
|
-
await ctx.deleteFile(absPath);
|
|
1284
|
-
results.push(`Deleted: ${action.path}`);
|
|
1478
|
+
if (prior) {
|
|
1479
|
+
staged.set(absPath, { ...prior, content: null });
|
|
1480
|
+
}
|
|
1481
|
+
else {
|
|
1482
|
+
let original;
|
|
1483
|
+
try {
|
|
1484
|
+
original = await ctx.readFile(absPath);
|
|
1285
1485
|
}
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1486
|
+
catch (err) {
|
|
1487
|
+
failures.push(`FAILED Delete ${action.path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1488
|
+
continue;
|
|
1289
1489
|
}
|
|
1490
|
+
staged.set(absPath, { original, content: null, eol: '\n' });
|
|
1290
1491
|
}
|
|
1291
|
-
|
|
1292
|
-
// v1.7.298 right-way fix: don't bail the whole patch on
|
|
1293
|
-
// first failure. Log this action's failure and try the rest
|
|
1294
|
-
// — model can re-emit just the failed actions.
|
|
1295
|
-
results.push(`FAILED Delete ${action.path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1296
|
-
}
|
|
1492
|
+
pending.push({ absPath, note: `Deleted: ${action.path}` });
|
|
1297
1493
|
continue;
|
|
1298
1494
|
}
|
|
1299
1495
|
if (action.kind === 'add') {
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1496
|
+
const addLines = addFileLines(action.lines);
|
|
1497
|
+
const content = addLines.join('\n') + (addLines.length > 0 ? '\n' : '');
|
|
1498
|
+
let original = prior ? prior.original : null;
|
|
1499
|
+
if (!prior) {
|
|
1500
|
+
try {
|
|
1501
|
+
original = await ctx.readFile(absPath);
|
|
1502
|
+
}
|
|
1503
|
+
catch {
|
|
1504
|
+
original = null;
|
|
1505
|
+
}
|
|
1307
1506
|
}
|
|
1507
|
+
staged.set(absPath, { original, content, eol: '\n' });
|
|
1508
|
+
pending.push({ absPath, note: `Added: ${action.path} (${addLines.length} lines)` });
|
|
1308
1509
|
continue;
|
|
1309
1510
|
}
|
|
1310
|
-
// Update:
|
|
1311
|
-
if (ctx.hasFileBeenRead && !ctx.hasFileBeenRead(absPath)) {
|
|
1312
|
-
|
|
1511
|
+
// Update: read-before-edit guard applies to files on disk.
|
|
1512
|
+
if (!prior && ctx.hasFileBeenRead && !ctx.hasFileBeenRead(absPath)) {
|
|
1513
|
+
failures.push(`FAILED Update ${action.path}: read this file with read_file first — apply_patch's "find" strings must match verbatim, which fails on unread files.`);
|
|
1313
1514
|
continue;
|
|
1314
1515
|
}
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
before = await ctx.readFile(absPath);
|
|
1318
|
-
}
|
|
1319
|
-
catch (err) {
|
|
1320
|
-
results.push(`FAILED Update ${action.path}: cannot read (${err instanceof Error ? err.message : String(err)})`);
|
|
1516
|
+
if (prior && prior.content === null) {
|
|
1517
|
+
failures.push(`FAILED Update ${action.path}: the file is deleted earlier in this same patch.`);
|
|
1321
1518
|
continue;
|
|
1322
1519
|
}
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
// when later hunks would have applied cleanly. The model then
|
|
1327
|
-
// had to regenerate the whole patch. Now: try each hunk, apply
|
|
1328
|
-
// those that match cleanly, report the rest with enough detail
|
|
1329
|
-
// (preview + fuzzy-match attempt notes) for the model to fix
|
|
1330
|
-
// just the failed hunks on retry. Per-hunk also adds a
|
|
1331
|
-
// whitespace-tolerant fallback: when exact match misses, retry
|
|
1332
|
-
// after collapsing whitespace runs in BOTH the file and the
|
|
1333
|
-
// find string — if that produces a unique match, use the
|
|
1334
|
-
// matched-region positions to splice in the replacement.
|
|
1335
|
-
let after = before;
|
|
1336
|
-
let hunksApplied = 0;
|
|
1337
|
-
let hunksFailed = 0;
|
|
1338
|
-
const hunkFailureNotes = [];
|
|
1339
|
-
for (let hi = 0; hi < action.hunks.length; hi++) {
|
|
1340
|
-
const hunk = action.hunks[hi];
|
|
1341
|
-
const contextCount = hunk.filter((item) => item.kind === 'context').length;
|
|
1342
|
-
const resolved = resolvePatchHunk(hunk, after);
|
|
1343
|
-
const { find, occurrences } = resolved;
|
|
1344
|
-
let { replace } = resolved;
|
|
1345
|
-
if (!find) {
|
|
1346
|
-
hunksFailed++;
|
|
1347
|
-
hunkFailureNotes.push(`hunk #${hi + 1}: empty (no removed lines and no context)`);
|
|
1348
|
-
continue;
|
|
1349
|
-
}
|
|
1350
|
-
if (occurrences === 1) {
|
|
1351
|
-
// Function replacer: a string one would expand `$&`, `$$`, `$1` in the patch text.
|
|
1352
|
-
after = after.replace(find, () => replace);
|
|
1353
|
-
hunksApplied++;
|
|
1354
|
-
continue;
|
|
1355
|
-
}
|
|
1356
|
-
if (occurrences > 1) {
|
|
1357
|
-
hunksFailed++;
|
|
1358
|
-
hunkFailureNotes.push(`hunk #${hi + 1}: matches ${occurrences} places — add more context to make it unique`);
|
|
1359
|
-
continue;
|
|
1360
|
-
}
|
|
1361
|
-
// occurrences === 0: try whitespace-tolerant fallback. Collapse
|
|
1362
|
-
// every run of whitespace within a line to a single space (but
|
|
1363
|
-
// keep newlines as line separators) on BOTH sides, search,
|
|
1364
|
-
// and if there's a unique match recover the original byte range
|
|
1365
|
-
// in the file and splice. This catches indentation drift /
|
|
1366
|
-
// trailing-whitespace differences without compromising the
|
|
1367
|
-
// multi-match safety.
|
|
1368
|
-
const normalize = (s) => s.split('\n').map((l) => l.replace(/[ \t]+/g, ' ').trimEnd()).join('\n');
|
|
1369
|
-
const normalizedFile = normalize(after);
|
|
1370
|
-
const normalizedFind = normalize(find);
|
|
1371
|
-
const normalOccurrences = normalizedFile.split(normalizedFind).length - 1;
|
|
1372
|
-
if (normalOccurrences === 1) {
|
|
1373
|
-
// Map the normalized match back to a real range in `after`.
|
|
1374
|
-
// The simplest correct approach: walk `after` line-by-line,
|
|
1375
|
-
// accumulating normalized text, and find the line index
|
|
1376
|
-
// where the normalized window matches. Then slice the
|
|
1377
|
-
// original bytes at that line range and replace with `replace`.
|
|
1378
|
-
const afterLines = after.split('\n');
|
|
1379
|
-
const findLineCount = find.split('\n').length;
|
|
1380
|
-
let matchedStart = -1;
|
|
1381
|
-
for (let i = 0; i + findLineCount <= afterLines.length; i++) {
|
|
1382
|
-
const window = afterLines.slice(i, i + findLineCount).join('\n');
|
|
1383
|
-
if (normalize(window) === normalizedFind) {
|
|
1384
|
-
matchedStart = i;
|
|
1385
|
-
break;
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
if (matchedStart >= 0) {
|
|
1389
|
-
// A whitespace-tolerant match says nothing about the marker
|
|
1390
|
-
// spelling. When every matched file line is indented exactly
|
|
1391
|
-
// one space less than the patch's line, the model wrote
|
|
1392
|
-
// "marker + space": drop that space from the added lines too.
|
|
1393
|
-
if (resolved.spelling === 'one-char') {
|
|
1394
|
-
// Removed lines only: context lines may be spelled either way.
|
|
1395
|
-
const findKinds = hunk.filter((item) => item.kind !== 'added').map((item) => item.kind);
|
|
1396
|
-
const findWindow = find.split('\n');
|
|
1397
|
-
const fileWindow = afterLines.slice(matchedStart, matchedStart + findLineCount);
|
|
1398
|
-
const pairs = findWindow
|
|
1399
|
-
.map((l, i) => [l, fileWindow[i] ?? '', findKinds[i]])
|
|
1400
|
-
.filter(([l, , kind]) => kind === 'removed' && l.trim().length > 0);
|
|
1401
|
-
const offByOne = pairs.length > 0 &&
|
|
1402
|
-
pairs.every(([l, f]) => leadingSpaces(l) === leadingSpaces(f) + 1 && !/^\s*\t/.test(f));
|
|
1403
|
-
if (offByOne) {
|
|
1404
|
-
replace = hunk
|
|
1405
|
-
.filter((item) => item.kind !== 'removed')
|
|
1406
|
-
.map((item) => (item.kind === 'added' ? dropMarkerSpace(item.text) : item.text))
|
|
1407
|
-
.join('\n');
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
const replaceLineCount = replace.split('\n').length;
|
|
1411
|
-
const replacedLines = [
|
|
1412
|
-
...afterLines.slice(0, matchedStart),
|
|
1413
|
-
...replace.split('\n'),
|
|
1414
|
-
...afterLines.slice(matchedStart + findLineCount)
|
|
1415
|
-
];
|
|
1416
|
-
after = replacedLines.join('\n');
|
|
1417
|
-
hunksApplied++;
|
|
1418
|
-
void replaceLineCount;
|
|
1419
|
-
continue;
|
|
1420
|
-
}
|
|
1421
|
-
}
|
|
1422
|
-
hunksFailed++;
|
|
1423
|
-
const preview = find.length > 160 ? find.slice(0, 160) + '…' : find;
|
|
1424
|
-
hunkFailureNotes.push(`hunk #${hi + 1}: text not found (${contextCount} context line${contextCount === 1 ? '' : 's'} provided). ` +
|
|
1425
|
-
`Tried to find:\n${preview.split('\n').map((l) => ` ${l}`).join('\n')}`);
|
|
1520
|
+
let entry;
|
|
1521
|
+
if (prior) {
|
|
1522
|
+
entry = prior;
|
|
1426
1523
|
}
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
// the failure than to write a stale snapshot.
|
|
1430
|
-
if (hunksApplied > 0) {
|
|
1524
|
+
else {
|
|
1525
|
+
let original;
|
|
1431
1526
|
try {
|
|
1432
|
-
await ctx.
|
|
1433
|
-
const lineDelta = after.split('\n').length - before.split('\n').length;
|
|
1434
|
-
const tail = hunksFailed > 0
|
|
1435
|
-
? ` — ${hunksApplied}/${action.hunks.length} hunks applied, ${hunksFailed} skipped:\n ${hunkFailureNotes.join('\n ')}`
|
|
1436
|
-
: ` (${action.hunks.length} hunk${action.hunks.length === 1 ? '' : 's'}, ${lineDelta >= 0 ? '+' : ''}${lineDelta} lines)`;
|
|
1437
|
-
results.push(`${hunksFailed > 0 ? 'Partially updated' : 'Updated'}: ${action.path}${tail}`);
|
|
1527
|
+
original = await ctx.readFile(absPath);
|
|
1438
1528
|
}
|
|
1439
1529
|
catch (err) {
|
|
1440
|
-
|
|
1530
|
+
failures.push(`FAILED Update ${action.path}: cannot read (${err instanceof Error ? err.message : String(err)})`);
|
|
1531
|
+
continue;
|
|
1441
1532
|
}
|
|
1533
|
+
// Match and edit in LF; the file's dominant ending goes back on at write.
|
|
1534
|
+
const eol = (0, unified_patch_1.detectLineEnding)(original);
|
|
1535
|
+
entry = { original, content: eol === '\r\n' ? (0, unified_patch_1.toLf)(original) : original, eol };
|
|
1442
1536
|
}
|
|
1443
|
-
|
|
1444
|
-
|
|
1537
|
+
const before = entry.content;
|
|
1538
|
+
const applied = applyEnvelopeHunks(before, action.hunks);
|
|
1539
|
+
if (applied.failed.length > 0) {
|
|
1540
|
+
failures.push(`FAILED Update ${action.path}: ${action.hunks.length - applied.failed.length}/${action.hunks.length} hunks matched, ${applied.failed.length} did not:\n ${applied.failed.join('\n ')}`);
|
|
1541
|
+
continue;
|
|
1445
1542
|
}
|
|
1543
|
+
staged.set(absPath, { ...entry, content: applied.after });
|
|
1544
|
+
const lineDelta = applied.after.split('\n').length - before.split('\n').length;
|
|
1545
|
+
pending.push({
|
|
1546
|
+
absPath,
|
|
1547
|
+
note: `Updated: ${action.path} (${action.hunks.length} hunk${action.hunks.length === 1 ? '' : 's'}, ${lineDelta >= 0 ? '+' : ''}${lineDelta} lines)`
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
if (failures.length > 0) {
|
|
1551
|
+
const okCount = actions.length - failures.length;
|
|
1552
|
+
const summary = `apply_patch wrote nothing: ${failures.length} of ${actions.length} action${actions.length === 1 ? '' : 's'} failed, and a patch is applied whole or not at all. ` +
|
|
1553
|
+
`Fix the failing hunks below (re-read the file and copy its current text verbatim) and re-send the whole patch${okCount > 0 ? ` — the ${okCount} other action${okCount === 1 ? '' : 's'} matched and will apply once these do` : ''}.`;
|
|
1554
|
+
return { output: `${summary}\n\n${failures.join('\n')}`, isError: true };
|
|
1555
|
+
}
|
|
1556
|
+
const commit = await commitStagedFiles(staged, ctx);
|
|
1557
|
+
if (!commit.ok) {
|
|
1558
|
+
return {
|
|
1559
|
+
output: `apply_patch failed while writing: FAILED ${commit.failure}\n${commit.rollbackNote}`,
|
|
1560
|
+
isError: true
|
|
1561
|
+
};
|
|
1446
1562
|
}
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
// landed instead of retrying the whole patch.
|
|
1451
|
-
const totalFailures = results.filter((r) => r.startsWith('FAILED ')).length;
|
|
1452
|
-
const allFailed = totalFailures === results.length;
|
|
1453
|
-
const summary = allFailed
|
|
1454
|
-
? `apply_patch could not land any changes. Inspect the per-action notes below, then either re-emit only the failing hunks with more context (verify whitespace matches read_file output exactly) or fall back to apply_edit for individual lines.`
|
|
1455
|
-
: totalFailures > 0
|
|
1456
|
-
? `apply_patch partially applied (${actions.length - totalFailures}/${actions.length} actions changed the file). Failed actions list specific hunks; retry just those.`
|
|
1457
|
-
: `Patch applied successfully (${actions.length} action${actions.length === 1 ? '' : 's'}). Do not restate the changes — the user can see the diff. Move on to the next pending task or summarize briefly if done.`;
|
|
1563
|
+
const results = pending.map((p) => (commit.blanked.has(p.absPath) && p.note.startsWith('Deleted: ')
|
|
1564
|
+
? `Deleted (blanked — host does not support hard delete; run \`rm ${p.note.slice('Deleted: '.length)}\` via run_command to remove the empty file): ${p.note.slice('Deleted: '.length)}`
|
|
1565
|
+
: p.note));
|
|
1458
1566
|
return {
|
|
1459
|
-
output:
|
|
1460
|
-
isError:
|
|
1567
|
+
output: `Patch applied successfully (${actions.length} action${actions.length === 1 ? '' : 's'}). Do not restate the changes — the user can see the diff. Move on to the next pending task or summarize briefly if done.\n\n${results.join('\n')}`,
|
|
1568
|
+
isError: false
|
|
1461
1569
|
};
|
|
1462
1570
|
}
|
|
1463
1571
|
};
|
|
@@ -1557,48 +1665,59 @@ function introducedNewErrors(before, after) {
|
|
|
1557
1665
|
* it had applied, and left the call site in the other file unchanged (BanditBench
|
|
1558
1666
|
* 2026-10-05, edit.rename_across_files).
|
|
1559
1667
|
*
|
|
1560
|
-
*
|
|
1561
|
-
*
|
|
1562
|
-
*
|
|
1668
|
+
* The whole diff is atomic: every file is staged (read, every hunk applied, validated)
|
|
1669
|
+
* before anything is written, and one failing file means nothing is written and the call
|
|
1670
|
+
* is an error naming it. Writing the files that applied and skipping the rest (the
|
|
1671
|
+
* earlier behaviour) left a rename with its definition changed and its call sites not.
|
|
1563
1672
|
*/
|
|
1564
1673
|
async function executeUnifiedDiffPatch(patchText, pathOverride, ctx) {
|
|
1565
1674
|
const sections = (0, unified_patch_1.splitUnifiedPatchByFile)(patchText);
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
}
|
|
1675
|
+
const single = sections.length <= 1;
|
|
1676
|
+
const staged = new Map();
|
|
1569
1677
|
// Several files: every section names its own path, so an explicit `path` (meant for a
|
|
1570
1678
|
// diff without headers) does not apply.
|
|
1571
|
-
const
|
|
1572
|
-
for (const section of sections) {
|
|
1679
|
+
const stages = [];
|
|
1680
|
+
for (const section of single ? [patchText] : sections) {
|
|
1573
1681
|
const header = /^\+\+\+ (?:b\/)?(.+?)\s*$/m.exec(section) ?? /^--- (?:a\/)?(.+?)\s*$/m.exec(section);
|
|
1574
|
-
const
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1682
|
+
const stage = await stageUnifiedDiffForFile(section, single ? pathOverride : undefined, ctx, staged);
|
|
1683
|
+
if (stage.ok) {
|
|
1684
|
+
const prior = staged.get(stage.absPath);
|
|
1685
|
+
staged.set(stage.absPath, { original: prior ? prior.original : stage.original, content: stage.next, eol: stage.eol });
|
|
1686
|
+
}
|
|
1687
|
+
stages.push({ file: header?.[1] ?? '(no path)', stage });
|
|
1688
|
+
}
|
|
1689
|
+
const failed = stages.filter((s) => !s.stage.ok);
|
|
1690
|
+
if (failed.length > 0) {
|
|
1691
|
+
if (single) {
|
|
1692
|
+
return { output: failed[0].stage.output, isError: true };
|
|
1693
|
+
}
|
|
1694
|
+
const body = failed.map((s) => `FAILED "${s.file}" — ${s.stage.output}`).join('\n\n');
|
|
1695
|
+
const okCount = stages.length - failed.length;
|
|
1696
|
+
const summary = okCount === 0
|
|
1697
|
+
? `apply_patch failed for all ${stages.length} files in the diff. Nothing was written.`
|
|
1698
|
+
: `apply_patch wrote nothing: ${failed.length} of ${stages.length} files failed, and a diff is applied whole or not at all. Fix ${failed.length === 1 ? 'that file' : 'those files'} and re-send the whole diff — the ${okCount} other file${okCount === 1 ? '' : 's'} matched and will apply once ${failed.length === 1 ? 'it does' : 'they do'}.`;
|
|
1699
|
+
return { output: `${summary}\n\n${body}`, isError: true };
|
|
1700
|
+
}
|
|
1701
|
+
const commit = await commitStagedFiles(staged, ctx);
|
|
1702
|
+
if (!commit.ok) {
|
|
1703
|
+
return { output: `apply_patch failed while writing: FAILED ${commit.failure}\n${commit.rollbackNote}`, isError: true };
|
|
1704
|
+
}
|
|
1705
|
+
const body = stages.map((s) => s.stage.summary).join('\n\n');
|
|
1706
|
+
return { output: body, isError: false };
|
|
1587
1707
|
}
|
|
1588
1708
|
/**
|
|
1589
|
-
*
|
|
1590
|
-
* `+++ b/<path>` header unless the caller passed an explicit `path`
|
|
1591
|
-
* param. We deliberately reuse the same
|
|
1592
|
-
*
|
|
1593
|
-
*
|
|
1594
|
-
* pipeline.
|
|
1709
|
+
* Stage a single-file unified-diff payload: read, apply every hunk, validate — no write.
|
|
1710
|
+
* Path is read from the `+++ b/<path>` header unless the caller passed an explicit `path`
|
|
1711
|
+
* param. We deliberately reuse the same language-adapter validation as apply_edit —
|
|
1712
|
+
* apply_patch is a different INPUT format, not a different write pipeline. A file an
|
|
1713
|
+
* earlier section of the same diff already changed is staged on top of that change.
|
|
1595
1714
|
*/
|
|
1596
|
-
async function
|
|
1715
|
+
async function stageUnifiedDiffForFile(patchText, pathOverride, ctx, staged) {
|
|
1597
1716
|
const parsed = (0, unified_patch_1.parseUnifiedPatch)(patchText);
|
|
1598
1717
|
if (!parsed) {
|
|
1599
1718
|
return {
|
|
1600
|
-
|
|
1601
|
-
|
|
1719
|
+
ok: false,
|
|
1720
|
+
output: 'apply_patch rejected: input looked like a unified diff but contains no `@@` hunks. Emit at least one hunk header with the form `@@ -<old_start>,<old_count> +<new_start>,<new_count> @@`.'
|
|
1602
1721
|
};
|
|
1603
1722
|
}
|
|
1604
1723
|
// Resolve path: explicit param wins, then `+++ b/<path>` header,
|
|
@@ -1608,8 +1727,8 @@ async function executeUnifiedDiffForFile(patchText, pathOverride, ctx) {
|
|
|
1608
1727
|
const relPath = (pathOverride ?? stripped ?? '').trim();
|
|
1609
1728
|
if (!relPath) {
|
|
1610
1729
|
return {
|
|
1611
|
-
|
|
1612
|
-
|
|
1730
|
+
ok: false,
|
|
1731
|
+
output: 'apply_patch rejected: no path. The unified diff has no `+++ b/<path>` header AND no explicit `path` param was provided. Either include the headers or pass `path` alongside the patch.'
|
|
1613
1732
|
};
|
|
1614
1733
|
}
|
|
1615
1734
|
const absPath = isAbsolutePath(relPath) ? relPath : `${ctx.workspaceRoot}/${relPath}`;
|
|
@@ -1624,12 +1743,25 @@ async function executeUnifiedDiffForFile(patchText, pathOverride, ctx) {
|
|
|
1624
1743
|
// the first unread file, and burned an iteration re-reading. The
|
|
1625
1744
|
// hint about "did you read this first?" still fires below when the
|
|
1626
1745
|
// patch fails AND the file hasn't been read.
|
|
1746
|
+
const prior = staged.get(absPath);
|
|
1747
|
+
let original;
|
|
1748
|
+
let eol;
|
|
1627
1749
|
let before;
|
|
1628
|
-
|
|
1629
|
-
|
|
1750
|
+
if (prior && prior.content !== null && prior.original !== null) {
|
|
1751
|
+
original = prior.original;
|
|
1752
|
+
eol = prior.eol;
|
|
1753
|
+
before = prior.content;
|
|
1630
1754
|
}
|
|
1631
|
-
|
|
1632
|
-
|
|
1755
|
+
else {
|
|
1756
|
+
try {
|
|
1757
|
+
original = await ctx.readFile(absPath);
|
|
1758
|
+
}
|
|
1759
|
+
catch (err) {
|
|
1760
|
+
return { ok: false, output: `Error reading "${relPath}": ${err instanceof Error ? err.message : String(err)}` };
|
|
1761
|
+
}
|
|
1762
|
+
// Match and edit in LF; the file's dominant ending goes back on at write.
|
|
1763
|
+
eol = (0, unified_patch_1.detectLineEnding)(original);
|
|
1764
|
+
before = eol === '\r\n' ? (0, unified_patch_1.toLf)(original) : original;
|
|
1633
1765
|
}
|
|
1634
1766
|
const result = (0, unified_patch_1.applyParsedPatch)(before, parsed);
|
|
1635
1767
|
if (!result.ok) {
|
|
@@ -1638,41 +1770,36 @@ async function executeUnifiedDiffForFile(patchText, pathOverride, ctx) {
|
|
|
1638
1770
|
? ''
|
|
1639
1771
|
: `\n\nYou have not called read_file on "${relPath}" in this conversation. If your hunk context was reconstructed from memory, that's almost certainly why the match failed — call read_file first, then retry with the verbatim text.`;
|
|
1640
1772
|
const ctxLine = result.contextSnippet ? `\n\nFile content near the expected position:\n${result.contextSnippet}` : '';
|
|
1641
|
-
return {
|
|
1642
|
-
output: `apply_patch failed: ${result.reason}${readHint}${ctxLine}`,
|
|
1643
|
-
isError: true
|
|
1644
|
-
};
|
|
1773
|
+
return { ok: false, output: `apply_patch failed: ${result.reason}${readHint}${ctxLine}` };
|
|
1645
1774
|
}
|
|
1646
1775
|
if (result.next === before) {
|
|
1647
|
-
return { output: 'apply_patch produced no change. Either the patch is empty or it duplicates content already in the file.'
|
|
1776
|
+
return { ok: false, output: 'apply_patch produced no change. Either the patch is empty or it duplicates content already in the file.' };
|
|
1648
1777
|
}
|
|
1649
1778
|
if (ctx.languageAdapters) {
|
|
1650
|
-
const afterValidation = await ctx.languageAdapters.validate(absPath, result.next, ctx);
|
|
1779
|
+
const afterValidation = await ctx.languageAdapters.validate(absPath, (0, unified_patch_1.withLineEnding)(result.next, eol), ctx);
|
|
1651
1780
|
if (!afterValidation.ok) {
|
|
1652
1781
|
// Pre-existing-error guard — same as apply_edit. Don't block a
|
|
1653
1782
|
// patch that targets the comparison-grid bug just because the
|
|
1654
1783
|
// file ALSO had unrelated TypeScript rot the user hasn't gotten
|
|
1655
1784
|
// to. See introducedNewErrors() above for the rationale.
|
|
1656
|
-
const beforeValidation = await ctx.languageAdapters.validate(absPath, before, ctx);
|
|
1785
|
+
const beforeValidation = await ctx.languageAdapters.validate(absPath, (0, unified_patch_1.withLineEnding)(before, eol), ctx);
|
|
1657
1786
|
if (introducedNewErrors(beforeValidation.error, afterValidation.error)) {
|
|
1658
1787
|
return {
|
|
1659
|
-
|
|
1660
|
-
|
|
1788
|
+
ok: false,
|
|
1789
|
+
output: `Validation failed after apply_patch on "${relPath}":\n${afterValidation.error}\n\nThe file was NOT written. Fix the patch and retry.`
|
|
1661
1790
|
};
|
|
1662
1791
|
}
|
|
1663
1792
|
}
|
|
1664
1793
|
}
|
|
1665
|
-
try {
|
|
1666
|
-
await ctx.writeFile(absPath, result.next);
|
|
1667
|
-
}
|
|
1668
|
-
catch (err) {
|
|
1669
|
-
return { output: `Error writing "${relPath}": ${err instanceof Error ? err.message : String(err)}`, isError: true };
|
|
1670
|
-
}
|
|
1671
1794
|
const lineCount = result.next.split('\n').length;
|
|
1672
1795
|
const hunkCount = parsed.hunks.length;
|
|
1673
1796
|
return {
|
|
1674
|
-
|
|
1675
|
-
|
|
1797
|
+
ok: true,
|
|
1798
|
+
absPath,
|
|
1799
|
+
original,
|
|
1800
|
+
next: result.next,
|
|
1801
|
+
eol,
|
|
1802
|
+
summary: `Applied ${hunkCount} hunk${hunkCount === 1 ? '' : 's'} to "${relPath}" (${lineCount} lines after).`
|
|
1676
1803
|
};
|
|
1677
1804
|
}
|
|
1678
1805
|
/**
|