@criogaid/pi-hashline-edit 0.1.3 → 0.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 +77 -23
- package/package.json +1 -1
- package/src/core/apply.test.ts +87 -10
- package/src/core/apply.ts +106 -84
- package/src/core/lines.test.ts +12 -1
- package/src/core/lines.ts +43 -1
- package/src/core/ranges.test.ts +28 -0
- package/src/core/ranges.ts +25 -0
- package/src/core/text.ts +5 -0
- package/src/core/types.ts +37 -20
- package/src/integration/grep-rg.test.ts +188 -1
- package/src/pi/action-fusion.test.ts +3 -1
- package/src/pi/action-fusion.ts +38 -35
- package/src/pi/anchor-format.test.ts +30 -0
- package/src/pi/anchor-format.ts +28 -0
- package/src/pi/config.ts +1 -1
- package/src/pi/edit-tool.ts +91 -100
- package/src/pi/execute.test.ts +239 -14
- package/src/pi/failure-context.test.ts +99 -62
- package/src/pi/failure-context.ts +67 -64
- package/src/pi/failure-path.test.ts +20 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/fusion-card.test.ts +38 -1
- package/src/pi/fusion-card.ts +41 -17
- package/src/pi/grep-tool.ts +84 -55
- package/src/pi/grep.test.ts +77 -6
- package/src/pi/mutation-result.ts +48 -9
- package/src/pi/path.ts +22 -0
- package/src/pi/pi.test.ts +64 -2
- package/src/pi/read-tool.ts +9 -30
- package/src/pi/registration.test.ts +28 -1
- package/src/pi/render.test.ts +111 -0
- package/src/pi/render.ts +30 -6
- package/src/pi/replace-tool.ts +144 -140
- package/src/pi/replace.test.ts +193 -1
- package/src/pi/result-safety.test.ts +241 -8
- package/src/pi/rg-line-filter.test.ts +7 -1
- package/src/pi/rg-line-filter.ts +10 -12
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/rg-text-view.ts +88 -0
- package/src/pi/write-tool.ts +13 -47
- package/src/pi/write.test.ts +25 -36
package/src/pi/edit-tool.ts
CHANGED
|
@@ -19,25 +19,26 @@
|
|
|
19
19
|
* @module pi-hashline-edit/pi
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import {
|
|
22
|
+
import { truncateHead, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
23
23
|
import { Type, type Static } from "typebox";
|
|
24
|
-
import { Text } from "@earendil-works/pi-tui";
|
|
25
|
-
import { readFile } from "node:fs/promises";
|
|
26
24
|
import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
27
|
-
import {
|
|
28
|
-
import { applyEdits
|
|
25
|
+
import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
|
|
26
|
+
import { applyEdits } from "../core/index.ts";
|
|
29
27
|
import { splitLines } from "../core/lines.ts";
|
|
30
28
|
import type { ApplyFailure, Edit } from "../core/types.ts";
|
|
31
|
-
import { canonicalPath } from "./
|
|
29
|
+
import { canonicalPath } from "./path.ts";
|
|
32
30
|
import { getState } from "./state.ts";
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
31
|
+
import { ANCHOR_PATTERN, createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
|
|
32
|
+
import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
33
|
+
import { formatAmbiguousCandidateNeighborhoods, MAX_AMBIGUOUS_CANDIDATES, MAX_RECOVERY_CANDIDATE_BYTES } from "./failure-context.ts";
|
|
34
|
+
import { appendMutationAnchors, finalizeMutationResult, formatMutationAnchors, generateMutationDetails, postProcessMutation } from "./mutation-result.ts";
|
|
36
35
|
|
|
37
|
-
/**
|
|
38
|
-
|
|
36
|
+
/** Keep independent byte budgets for failure details and input-anchor checks. */
|
|
37
|
+
function boundDiagnostic(message: string, notice: string): string {
|
|
38
|
+
const bounded = truncateHead(message, { maxBytes: 16 * 1024 - Buffer.byteLength(notice) });
|
|
39
|
+
return bounded.content + (bounded.truncated ? notice : "");
|
|
40
|
+
}
|
|
39
41
|
|
|
40
|
-
const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
|
|
41
42
|
|
|
42
43
|
function anchorRef(description: string) {
|
|
43
44
|
return Type.Optional(Type.String({ pattern: ANCHOR_PATTERN, description }));
|
|
@@ -91,14 +92,17 @@ type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: The
|
|
|
91
92
|
|
|
92
93
|
type EditOpInput = Static<typeof editOpSchema>;
|
|
93
94
|
|
|
94
|
-
/** Format
|
|
95
|
-
function
|
|
95
|
+
/** Format failure mappings and complete unique-candidate rows within the detail budget. */
|
|
96
|
+
function formatFailureDetails(
|
|
96
97
|
failure: ApplyFailure,
|
|
97
|
-
snapshot: Readonly<{ currentText: string;
|
|
98
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
99
|
+
candidateLines: ReadonlySet<number>,
|
|
98
100
|
): string {
|
|
99
101
|
if (failure.kind !== "anchor") return failure.message;
|
|
100
102
|
|
|
101
103
|
const lines: string[] = [];
|
|
104
|
+
const currentLines = splitLines(snapshot.currentText);
|
|
105
|
+
const shownCandidates = new Set(candidateLines);
|
|
102
106
|
let found = 0;
|
|
103
107
|
let ambiguous = 0;
|
|
104
108
|
let none = 0;
|
|
@@ -106,21 +110,35 @@ function formatFailure(
|
|
|
106
110
|
if (f.recovery.kind === "found") found++;
|
|
107
111
|
else if (f.recovery.kind === "ambiguous") ambiguous++;
|
|
108
112
|
else none++;
|
|
109
|
-
if (lines.length >= MAX_FAILURE_DETAILS) continue;
|
|
110
113
|
const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
|
|
114
|
+
const search = f.recovery.kind === "none" ? "" : f.recovery.scope === "local"
|
|
115
|
+
? "Search: local; matches outside the window were not checked." : "Search: full file.";
|
|
111
116
|
switch (f.recovery.kind) {
|
|
112
|
-
case "found":
|
|
113
|
-
|
|
117
|
+
case "found": {
|
|
118
|
+
const content = currentLines[f.recovery.newLine - 1];
|
|
119
|
+
const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
|
|
120
|
+
const row = content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
|
|
121
|
+
let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
|
|
122
|
+
if (!shownCandidates.has(f.recovery.newLine)) {
|
|
123
|
+
if (content !== undefined && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
|
|
124
|
+
detail += `\n${row}`;
|
|
125
|
+
shownCandidates.add(f.recovery.newLine);
|
|
126
|
+
} else {
|
|
127
|
+
detail += ` Candidate content exceeds ${MAX_RECOVERY_CANDIDATE_BYTES} bytes.`;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
lines.push(detail);
|
|
114
131
|
break;
|
|
132
|
+
}
|
|
115
133
|
case "ambiguous": {
|
|
116
|
-
const list = f.recovery.candidates.slice(0,
|
|
117
|
-
const more = f.recovery.candidates.length >
|
|
118
|
-
lines.push(`• ${where}: ambiguous checksum matches
|
|
134
|
+
const list = f.recovery.candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES).map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`).join(" / ");
|
|
135
|
+
const more = f.recovery.candidates.length > MAX_AMBIGUOUS_CANDIDATES ? ` (${f.recovery.candidates.length - MAX_AMBIGUOUS_CANDIDATES} more candidates omitted)` : "";
|
|
136
|
+
lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
|
|
119
137
|
break;
|
|
120
138
|
}
|
|
121
139
|
case "none":
|
|
122
140
|
lines.push(
|
|
123
|
-
`• ${where}:
|
|
141
|
+
`• ${where}: no checksum-matching candidate found. Use read to inspect the current file before retrying.` +
|
|
124
142
|
(f.current === null ? " Cited line is out of range." : ""),
|
|
125
143
|
);
|
|
126
144
|
break;
|
|
@@ -134,11 +152,33 @@ function formatFailure(
|
|
|
134
152
|
`Anchor mismatch: ${parts.join(", ")}.`,
|
|
135
153
|
"No changes written by this edit batch.",
|
|
136
154
|
...lines,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
155
|
+
].join("\n");
|
|
156
|
+
return boundDiagnostic(message, "\nDiagnostic output truncated at 16 KiB.");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
|
|
160
|
+
const rows = failure.checks.map((check) =>
|
|
161
|
+
`op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
|
|
162
|
+
);
|
|
163
|
+
const message = [
|
|
164
|
+
"Input-anchor checks (this snapshot):",
|
|
165
|
+
...rows,
|
|
166
|
+
"Anchor checks only; retries revalidate.",
|
|
167
|
+
].join("\n");
|
|
168
|
+
return boundDiagnostic(message, "\nAnchor-check output truncated at 16 KiB; omitted entries are not implied matched.");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Keep validation status and observation context visible even when failure details are truncated. */
|
|
172
|
+
function formatFailure(
|
|
173
|
+
failure: ApplyFailure,
|
|
174
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
175
|
+
): string {
|
|
176
|
+
const candidateNeighborhoods = failure.kind === "anchor"
|
|
177
|
+
? formatAmbiguousCandidateNeighborhoods(snapshot.currentText, failure.failures, snapshot.anchors)
|
|
178
|
+
: { text: "", shownLines: new Set<number>() };
|
|
179
|
+
const guidance = failure.kind === "anchor"
|
|
180
|
+
? "\nCheck the intended target before retrying; use read or grep for omitted or additional context." : "";
|
|
181
|
+
return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}\n${formatAnchorChecks(failure, snapshot.anchors)}${candidateNeighborhoods.text}${guidance}`;
|
|
142
182
|
}
|
|
143
183
|
|
|
144
184
|
/** Translate JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
|
|
@@ -177,12 +217,12 @@ function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } |
|
|
|
177
217
|
}
|
|
178
218
|
|
|
179
219
|
/**
|
|
180
|
-
*
|
|
181
|
-
*
|
|
220
|
+
* Return compact tokens for changed caller-supplied rows, retaining content for deletion successors.
|
|
221
|
+
* Uses the applicator's final indices so mixed batches do not need a second position calculation.
|
|
182
222
|
*/
|
|
183
|
-
function formatUpdatedAnchors(newText: string, touched: readonly number[],
|
|
223
|
+
function formatUpdatedAnchors(before: string, newText: string, touched: readonly number[], contextLines: readonly number[], anchors: AnchorFormatter): string {
|
|
184
224
|
const idxs = [...new Set(touched)].sort((a, b) => a - b);
|
|
185
|
-
return formatMutationAnchors(splitLines(newText), idxs,
|
|
225
|
+
return formatMutationAnchors(splitLines(before), splitLines(newText), idxs, anchors, "Updated anchors:", new Set(contextLines));
|
|
186
226
|
}
|
|
187
227
|
|
|
188
228
|
/** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
|
|
@@ -202,24 +242,18 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
202
242
|
name: "edit" as const,
|
|
203
243
|
label: "edit",
|
|
204
244
|
description:
|
|
205
|
-
"Edit file lines using content-verified anchors. Returns fresh anchors for subsequent edits.
|
|
245
|
+
"Edit file lines using content-verified anchors. Returns fresh anchors for subsequent edits. Anchor failures report input-anchor status and bounded current-file context. Inspect recovery candidates before retrying; retries always revalidate anchors and never run automatically.",
|
|
206
246
|
promptSnippet: "Edit file lines using verified anchors",
|
|
207
247
|
promptGuidelines: [
|
|
208
248
|
"Batch changes to the same file in one edit call.",
|
|
209
|
-
"
|
|
249
|
+
"Reuse prior anchors when their line number and content are unchanged. Re-read changed or shifted lines when no fresh anchor is available.",
|
|
210
250
|
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
211
251
|
],
|
|
212
252
|
parameters,
|
|
213
253
|
renderShell: "default" as const,
|
|
214
254
|
|
|
215
255
|
renderCall(args: EditParams, theme: any, context: any) {
|
|
216
|
-
|
|
217
|
-
// Stash the header for renderResult: the diff counts land after
|
|
218
|
-
// execution and are refreshed in place (renderResult's lastComponent
|
|
219
|
-
// is the result component, not this header)
|
|
220
|
-
if (context?.state) context.state.callText = text;
|
|
221
|
-
text.setText(editHeader(args, theme, context?.state?.diffCounts));
|
|
222
|
-
return text;
|
|
256
|
+
return renderMutationCall(args, theme, context, editHeader);
|
|
223
257
|
},
|
|
224
258
|
|
|
225
259
|
renderResult(result: any, options: any, theme: any, context: any) {
|
|
@@ -242,14 +276,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
242
276
|
(anchors) => { mutationAnchors = anchors; },
|
|
243
277
|
));
|
|
244
278
|
};
|
|
245
|
-
const finalizeMutation = (result: any, publishAnchors: boolean) => (
|
|
246
|
-
...result,
|
|
247
|
-
content: result.content.map((block: any, index: number) =>
|
|
248
|
-
index === 0 && block.type === "text"
|
|
249
|
-
? { ...block, text: `${block.text}${publishAnchors ? mutationAnchors : ""}` }
|
|
250
|
-
: block,
|
|
251
|
-
),
|
|
252
|
-
});
|
|
279
|
+
const finalizeMutation = (result: any, publishAnchors: boolean) => appendMutationAnchors(result, mutationAnchors, publishAnchors);
|
|
253
280
|
if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
|
|
254
281
|
return fusion({
|
|
255
282
|
toolCallId,
|
|
@@ -272,70 +299,34 @@ async function runHashline(
|
|
|
272
299
|
signal: AbortSignal | undefined,
|
|
273
300
|
onAnchors: (anchors: string) => void,
|
|
274
301
|
) {
|
|
275
|
-
const
|
|
302
|
+
const anchorFormatter = createAnchorFormatter();
|
|
303
|
+
const { shiftRadius } = getState().config;
|
|
276
304
|
|
|
277
|
-
|
|
278
|
-
let baseRevision: string;
|
|
279
|
-
try {
|
|
280
|
-
const currentBytes = await readFile(absPath);
|
|
281
|
-
baseRevision = byteRevision(currentBytes);
|
|
282
|
-
currentText = decodeEditableText(currentBytes);
|
|
283
|
-
} catch (e) {
|
|
284
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
285
|
-
throw new Error(`Error reading ${displayPath}: ${msg}`);
|
|
286
|
-
}
|
|
305
|
+
const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
|
|
287
306
|
// Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
|
|
288
307
|
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before apply.`);
|
|
289
308
|
|
|
290
309
|
const translated = toCoreEdits(editOps);
|
|
291
310
|
if (!translated.ok) throw new Error(translated.error);
|
|
292
311
|
|
|
293
|
-
//
|
|
294
|
-
//
|
|
295
|
-
//
|
|
296
|
-
|
|
297
|
-
// the batch are collected (nothing written on any failure).
|
|
298
|
-
const result = applyEdits(currentText, translated.edits, hashLen, shiftRadius);
|
|
312
|
+
// Recovery reports checksum candidates from nearby lines, then the whole file
|
|
313
|
+
// if needed. Every failed anchor still rejects the batch; callers inspect
|
|
314
|
+
// candidates and resubmit with fresh anchors.
|
|
315
|
+
const result = applyEdits(currentText, translated.edits, anchorFormatter.hashLen, shiftRadius);
|
|
299
316
|
if (!result.ok) {
|
|
300
|
-
throw new Error(formatFailure(result.failure, { currentText,
|
|
317
|
+
throw new Error(formatFailure(result.failure, { currentText, anchors: anchorFormatter }));
|
|
301
318
|
}
|
|
302
319
|
|
|
303
320
|
// Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
|
|
304
321
|
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before write.`);
|
|
305
322
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
if (e instanceof FileMutationError) throw e;
|
|
314
|
-
throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
let details: EditToolDetails & MutationVersions & { publication: PublicationStatus; revision: string };
|
|
318
|
-
let anchors: string;
|
|
319
|
-
try {
|
|
320
|
-
// Diff and anchor generation happens after publication; preserve that state on failure.
|
|
321
|
-
const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
322
|
-
const newLf = result.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
323
|
-
const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
|
|
324
|
-
details = {
|
|
325
|
-
diff,
|
|
326
|
-
patch: generateUnifiedPatch(displayPath, oldLf, newLf),
|
|
327
|
-
firstChangedLine,
|
|
328
|
-
publication,
|
|
329
|
-
...versions,
|
|
330
|
-
revision: versions.publishedRevision,
|
|
323
|
+
const versions = await commitReplacement(absPath, displayPath, result.text, baseRevision, signal);
|
|
324
|
+
return postProcessMutation("edit", versions.publication, () => {
|
|
325
|
+
const details = generateMutationDetails(displayPath, currentText, result.text, versions, versions.publication);
|
|
326
|
+
onAnchors(formatUpdatedAnchors(currentText, result.text, result.touchedLines, result.contextLines, anchorFormatter));
|
|
327
|
+
return {
|
|
328
|
+
content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)${result.changed ? "" : ", no net change"}).` }],
|
|
329
|
+
details,
|
|
331
330
|
};
|
|
332
|
-
|
|
333
|
-
onAnchors(anchors);
|
|
334
|
-
} catch (error) {
|
|
335
|
-
throw new FileMutationError("post_process", publication, `file was published but edit result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
336
|
-
}
|
|
337
|
-
return {
|
|
338
|
-
content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)).` }],
|
|
339
|
-
details,
|
|
340
|
-
};
|
|
331
|
+
});
|
|
341
332
|
}
|
package/src/pi/execute.test.ts
CHANGED
|
@@ -39,7 +39,7 @@ function h(text: string, line: number) {
|
|
|
39
39
|
|
|
40
40
|
/** Extract a `LINE#HASH` anchor from a read/edit result text block. */
|
|
41
41
|
function anchorLine(block: string, line: number) {
|
|
42
|
-
const m = new RegExp(`^${line}#([0-9A-Z]+)
|
|
42
|
+
const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
|
|
43
43
|
if (!m) throw new Error(`line ${line} anchor not found in block`);
|
|
44
44
|
return `${line}#${m[1]}`;
|
|
45
45
|
}
|
|
@@ -133,6 +133,7 @@ test("edit result returns Updated anchors that chain the next edit without a re-
|
|
|
133
133
|
assert.equal(r1.isError, undefined);
|
|
134
134
|
const out: string = r1.content[0].text;
|
|
135
135
|
assert.match(out, /Updated anchors/);
|
|
136
|
+
assert.doesNotMatch(out, /│/);
|
|
136
137
|
// second edit chains on the anchor returned by the first edit — no read in between
|
|
137
138
|
const r2: any = await call(edit, {
|
|
138
139
|
path: "f.txt",
|
|
@@ -198,23 +199,24 @@ test("edit on a line that changed externally → anchor mismatch", async () => {
|
|
|
198
199
|
});
|
|
199
200
|
});
|
|
200
201
|
|
|
201
|
-
test("unresolved
|
|
202
|
+
test("unresolved anchors require a fresh read and return no context rows", async () => {
|
|
202
203
|
await withDir(async (dir) => {
|
|
203
204
|
const file = join(dir, "recover.txt");
|
|
204
205
|
const observed = ["one", "two", "three", "four", "old marker", "six", "seven", "eight"].join("\n") + "\n";
|
|
205
206
|
await writeFile(file, ["one", "two", "three", "four", "changed", "six", "new marker", "eight"].join("\n") + "\n");
|
|
206
207
|
const edit = makeEditOverride(dir);
|
|
207
|
-
let retryAnchor = "";
|
|
208
208
|
await assert.rejects(call(edit, {
|
|
209
209
|
path: "recover.txt",
|
|
210
210
|
edits: [{ op: "replace", anchor: h(observed, 5), body: ["updated"] }],
|
|
211
211
|
}), (error: Error) => {
|
|
212
212
|
assert.match(error.message, /Anchor mismatch: 1 unresolved/);
|
|
213
213
|
assert.match(error.message, /No changes written by this edit batch/);
|
|
214
|
-
assert.match(error.message,
|
|
215
|
-
|
|
216
|
-
return
|
|
214
|
+
assert.match(error.message, /Use read to inspect the current file before retrying/);
|
|
215
|
+
assert.doesNotMatch(error.message, /^\d+#[0-9A-Z]+│|neighborhoods|Current-file context/m);
|
|
216
|
+
return true;
|
|
217
217
|
});
|
|
218
|
+
const read = await call(makeReadOverride(dir), { path: "recover.txt" });
|
|
219
|
+
const retryAnchor = anchorLine(read.content[0].text, 7);
|
|
218
220
|
await call(edit, { path: "recover.txt", edits: [{ op: "replace", anchor: retryAnchor, body: ["updated"] }] });
|
|
219
221
|
assert.equal(await readFile(file, "utf8"), "one\ntwo\nthree\nfour\nchanged\nsix\nupdated\neight\n");
|
|
220
222
|
});
|
|
@@ -432,6 +434,8 @@ test("read reports an oversized first row without suggesting an ineffective retr
|
|
|
432
434
|
assert.equal(result.details.truncation.outputLines, 0);
|
|
433
435
|
assert.match(result.content[0].text, /cannot return a complete anchor row/);
|
|
434
436
|
assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
|
|
437
|
+
assert.match(result.content[0].text, /Reducing limit cannot split a physical line/);
|
|
438
|
+
assert.match(result.content[0].text, /use bash to inspect it in chunks, or replace/);
|
|
435
439
|
}));
|
|
436
440
|
|
|
437
441
|
test("read preserves empty files and explicit limits above the native default", async () => withDir(async (dir) => {
|
|
@@ -486,17 +490,40 @@ test("invalid anchors and conflicting fields fail before changing the file", asy
|
|
|
486
490
|
assert.throws(() => validateToolArguments(edit as any, { type: "toolCall", id: "invalid", name: "edit", arguments: { path: "invalid.txt", edits: [invalid[0]] } as any }));
|
|
487
491
|
}));
|
|
488
492
|
|
|
489
|
-
test("
|
|
493
|
+
test("local and full-file recovery return copyable anchors without changing the rejected batch", async () => withDir(async (dir) => {
|
|
490
494
|
const original = "a\nb\n";
|
|
491
|
-
await writeFile(join(dir, "shift.txt"), "prefix\n" + original);
|
|
492
495
|
const edit = makeEditOverride(dir);
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
496
|
+
for (const prefixLines of [1, 40]) {
|
|
497
|
+
const prefix = "prefix\n".repeat(prefixLines);
|
|
498
|
+
await writeFile(join(dir, "shift.txt"), prefix + original);
|
|
499
|
+
let replacement = "";
|
|
500
|
+
await assert.rejects(call(edit, { path: "shift.txt", edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }] }), (error: Error) => {
|
|
501
|
+
replacement = new RegExp(`^(${prefixLines + 2}#[0-9A-Z]+)│b$`, "m").exec(error.message)?.[1] ?? "";
|
|
502
|
+
assert.match(error.message, /Check the intended target/);
|
|
503
|
+
assert.match(error.message, prefixLines === 1
|
|
504
|
+
? /Search: local; matches outside the window were not checked\./ : /Search: full file\./);
|
|
505
|
+
assert.doesNotMatch(error.message, prefixLines === 1 ? /Search: full file/ : /Search: local/);
|
|
506
|
+
assert.doesNotMatch(error.message, /neighborhoods/);
|
|
507
|
+
assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
|
|
508
|
+
return replacement !== "";
|
|
509
|
+
});
|
|
510
|
+
assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + original);
|
|
511
|
+
await call(edit, { path: "shift.txt", edits: [{ op: "replace", anchor: replacement, body: ["B"] }] });
|
|
512
|
+
assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + "a\nB\n");
|
|
513
|
+
}
|
|
514
|
+
}));
|
|
515
|
+
|
|
516
|
+
test("shifted-anchor recovery keeps the read fallback for oversized candidates", async () => withDir(async (dir) => {
|
|
517
|
+
const oversized = "x".repeat(4 * 1024);
|
|
518
|
+
const original = `a\n${oversized}\n`;
|
|
519
|
+
await writeFile(join(dir, "shift-large.txt"), `prefix\n${original}`);
|
|
520
|
+
const edit = makeEditOverride(dir);
|
|
521
|
+
await assert.rejects(call(edit, { path: "shift-large.txt", edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }] }), (error: Error) => {
|
|
522
|
+
assert.match(error.message, /Candidate content exceeds 4096 bytes/);
|
|
523
|
+
assert.match(error.message, /use read or grep/);
|
|
524
|
+
assert.doesNotMatch(error.message, new RegExp(`│x{${oversized.length}}`));
|
|
525
|
+
return true;
|
|
497
526
|
});
|
|
498
|
-
await call(edit, { path: "shift.txt", edits: [{ op: "replace", anchor: replacement, body: ["B"] }] });
|
|
499
|
-
assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), "prefix\na\nB\n");
|
|
500
527
|
}));
|
|
501
528
|
|
|
502
529
|
test("failed commands preserve mutation results and stay out of all main card renderers", async () => withDir(async (dir) => {
|
|
@@ -568,3 +595,201 @@ test("edit and replace reject NUL output without rewriting source bytes", async
|
|
|
568
595
|
await assert.rejects(call(makeReplaceTool(dir), { path: "output.txt", find: "before", replace: "bad\0text" }), /UNSUPPORTED_TEXT/);
|
|
569
596
|
assert.deepEqual(await readFile(target), original);
|
|
570
597
|
}));
|
|
598
|
+
|
|
599
|
+
test("failed edits expose input status and candidate code for a verified fused retry", async () => withDir(async (dir) => {
|
|
600
|
+
const original = Array.from({ length: 14 }, (_, index) => `line-${index + 1}`);
|
|
601
|
+
original[4] = "if (!fusion) throw new Error();";
|
|
602
|
+
original[5] = "const absolutePath = canonicalPath(cwd, path);";
|
|
603
|
+
const before = `prefix\n${original.join("\n")}\n`;
|
|
604
|
+
const file = join(dir, "candidate.txt");
|
|
605
|
+
await writeFile(file, before);
|
|
606
|
+
let commands = 0;
|
|
607
|
+
const fusion = createActionFusionExecutor(async () => { commands++; return "checked"; });
|
|
608
|
+
const edit = makeEditOverride(dir, fusion);
|
|
609
|
+
const stale = h(original.join("\n"), 5);
|
|
610
|
+
const stable = h(before, 12);
|
|
611
|
+
const candidate = h(before, 6);
|
|
612
|
+
let message = "";
|
|
613
|
+
await assert.rejects(edit.execute("failed", {
|
|
614
|
+
path: file,
|
|
615
|
+
edits: [
|
|
616
|
+
{ op: "insert_after", anchor: stale, body: ["const hashLen = 4;"] },
|
|
617
|
+
{ op: "replace", anchor: stable, body: ["changed"] },
|
|
618
|
+
],
|
|
619
|
+
then_run: { command: "check" },
|
|
620
|
+
}, undefined, undefined, { cwd: dir }), (error: Error) => { message = error.message; return true; });
|
|
621
|
+
assert.match(message, /then_run:skipped/);
|
|
622
|
+
assert.ok(message.includes(`op 0 / anchor / ${stale} / mismatched`));
|
|
623
|
+
assert.ok(message.includes(`op 1 / anchor / ${stable} / matched`));
|
|
624
|
+
assert.ok(message.includes(`checksum-matching candidate ${candidate}.`));
|
|
625
|
+
assert.equal(message.split(`${candidate}│${original[4]}`).length - 1, 1);
|
|
626
|
+
assert.doesNotMatch(message, /0 omitted|Limits:/);
|
|
627
|
+
assert.doesNotMatch(message, /neighborhoods|Current-file context/);
|
|
628
|
+
assert.equal((message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
|
|
629
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
630
|
+
assert.equal(commands, 0);
|
|
631
|
+
await edit.execute("retry", {
|
|
632
|
+
path: file,
|
|
633
|
+
edits: [
|
|
634
|
+
{ op: "insert_after", anchor: anchorLine(message, 6), body: ["const hashLen = 4;"] },
|
|
635
|
+
{ op: "replace", anchor: stable, body: ["changed"] },
|
|
636
|
+
],
|
|
637
|
+
then_run: { command: "check" },
|
|
638
|
+
}, undefined, undefined, { cwd: dir });
|
|
639
|
+
const expected = splitLines(before);
|
|
640
|
+
expected[11] = "changed";
|
|
641
|
+
expected.splice(6, 0, "const hashLen = 4;");
|
|
642
|
+
assert.equal(await readFile(file, "utf8"), `${expected.join("\n")}\n`);
|
|
643
|
+
assert.equal(commands, 1);
|
|
644
|
+
}));
|
|
645
|
+
|
|
646
|
+
test("ambiguous candidates include distinguishing neighborhoods for a verified retry", async () => withDir(async (dir) => {
|
|
647
|
+
const lines = Array.from({ length: 20 }, (_, index) => `line-${index + 1}`);
|
|
648
|
+
lines[3] = "function primary() {";
|
|
649
|
+
lines[4] = " return value;";
|
|
650
|
+
lines[13] = "function secondary() {";
|
|
651
|
+
lines[14] = " return value;";
|
|
652
|
+
const before = lines.join("\n") + "\n";
|
|
653
|
+
const file = join(dir, "ambiguous.txt");
|
|
654
|
+
await writeFile(file, before);
|
|
655
|
+
const edit = makeEditOverride(dir);
|
|
656
|
+
let context = "";
|
|
657
|
+
await assert.rejects(call(edit, { path: file, edits: [
|
|
658
|
+
{ op: "replace", anchor: h("header\n return value;\n", 2), body: [" return updated;"] },
|
|
659
|
+
] }), (error: Error) => {
|
|
660
|
+
assert.match(error.message, /ambiguous checksum matches/);
|
|
661
|
+
assert.match(error.message, /Search: local; matches outside the window were not checked\./);
|
|
662
|
+
assert.ok(error.message.includes(`"${h(before, 5)}" / "${h(before, 15)}"`));
|
|
663
|
+
context = error.message.split("Ambiguous-candidate neighborhoods")[1];
|
|
664
|
+
assert.ok(context);
|
|
665
|
+
assert.match(context, /@@ candidate-neighborhood lines 2-8 @@/);
|
|
666
|
+
assert.match(context, /@@ candidate-neighborhood lines 12-18 @@/);
|
|
667
|
+
assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
|
|
668
|
+
assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
|
|
669
|
+
assert.equal(anchorLine(context, 5), h(before, 5));
|
|
670
|
+
return true;
|
|
671
|
+
});
|
|
672
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
673
|
+
await call(edit, { path: file, edits: [{ op: "replace", anchor: anchorLine(context, 15), body: [" return updated;"] }] });
|
|
674
|
+
lines[14] = " return updated;";
|
|
675
|
+
assert.equal(await readFile(file, "utf8"), lines.join("\n") + "\n");
|
|
676
|
+
}));
|
|
677
|
+
|
|
678
|
+
test("input status distinguishes skipped checks and expires before the next retry", async () => withDir(async (dir) => {
|
|
679
|
+
const before = "a\nb\nc\n";
|
|
680
|
+
const file = join(dir, "checks.txt");
|
|
681
|
+
await writeFile(file, before);
|
|
682
|
+
const edit = makeEditOverride(dir);
|
|
683
|
+
const stable = h(before, 1);
|
|
684
|
+
await assert.rejects(call(edit, { path: file, edits: [{ op: "replace", anchor: stable, body: ["bad\nline"] }] }), (error: Error) => {
|
|
685
|
+
assert.ok(error.message.includes(`op 0 / anchor / ${stable} / not_checked`));
|
|
686
|
+
assert.doesNotMatch(error.message, /\/ matched/);
|
|
687
|
+
return true;
|
|
688
|
+
});
|
|
689
|
+
await assert.rejects(call(edit, { path: file, edits: [
|
|
690
|
+
{ op: "replace", anchor: stable, body: ["A"] },
|
|
691
|
+
{ op: "delete", anchor: h(before, 2), end: "3#ZZ" },
|
|
692
|
+
] }), (error: Error) => {
|
|
693
|
+
assert.ok(error.message.includes(`op 0 / anchor / ${stable} / matched`));
|
|
694
|
+
assert.match(error.message, /op 1 \/ end \/ 3#ZZ \/ mismatched/);
|
|
695
|
+
assert.match(error.message, /Anchor checks only; retries revalidate/);
|
|
696
|
+
return true;
|
|
697
|
+
});
|
|
698
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
699
|
+
await writeFile(file, "changed\nb\nc\n");
|
|
700
|
+
await assert.rejects(call(edit, { path: file, edits: [{ op: "replace", anchor: stable, body: ["A"] }] }), (error: Error) => {
|
|
701
|
+
assert.ok(error.message.includes(`op 0 / anchor / ${stable} / mismatched`));
|
|
702
|
+
return true;
|
|
703
|
+
});
|
|
704
|
+
assert.equal(await readFile(file, "utf8"), "changed\nb\nc\n");
|
|
705
|
+
}));
|
|
706
|
+
|
|
707
|
+
test("failed batches return more than forty checks and mappings when byte budgets allow", async () => withDir(async (dir) => {
|
|
708
|
+
const original = "a\ntarget\nz\n";
|
|
709
|
+
const before = `prefix\n${original}`;
|
|
710
|
+
const file = join(dir, "many-checks.txt");
|
|
711
|
+
await writeFile(file, before);
|
|
712
|
+
const edits = Array.from({ length: 45 }, () => ({ op: "replace", anchor: h(original, 2), body: ["changed"] }));
|
|
713
|
+
await assert.rejects(call(makeEditOverride(dir), { path: file, edits }), (error: Error) => {
|
|
714
|
+
assert.doesNotMatch(error.message, /truncated|failure details omitted|Anchor checks: \d+\/\d+/);
|
|
715
|
+
assert.equal((error.message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? []).length, 45);
|
|
716
|
+
assert.equal((error.message.match(/checksum-matching candidate/g) ?? []).length, 45);
|
|
717
|
+
assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
|
|
718
|
+
assert.doesNotMatch(error.message, /\/ matched/);
|
|
719
|
+
return true;
|
|
720
|
+
});
|
|
721
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
722
|
+
}));
|
|
723
|
+
|
|
724
|
+
test("compact edit anchors retain only untouched deletion successors in mixed batches", async () => withDir(async (dir) => {
|
|
725
|
+
const before = "a\nb\nc\nd\ne\nf\ng\n";
|
|
726
|
+
const file = join(dir, "mixed.txt");
|
|
727
|
+
await writeFile(file, before);
|
|
728
|
+
const edit = makeEditOverride(dir);
|
|
729
|
+
const result = await call(edit, { path: file, edits: [
|
|
730
|
+
{ op: "delete", anchor: h(before, 6) },
|
|
731
|
+
{ op: "replace", anchor: h(before, 4), body: ["D"] },
|
|
732
|
+
{ op: "delete", anchor: h(before, 3) },
|
|
733
|
+
{ op: "replace", anchor: h(before, 1), body: ["A", "X"] },
|
|
734
|
+
] });
|
|
735
|
+
const after = "A\nX\nb\nD\ne\ng\n";
|
|
736
|
+
assert.equal(await readFile(file, "utf8"), after);
|
|
737
|
+
const output = result.content[0].text;
|
|
738
|
+
assert.deepEqual(output.split("\n").filter((line: string) => /^\d+#/.test(line)), [
|
|
739
|
+
h(after, 1), h(after, 2), h(after, 4), `${h(after, 6)}│g`,
|
|
740
|
+
]);
|
|
741
|
+
await call(edit, { path: file, edits: [{ op: "replace", anchor: anchorLine(output, 6), body: ["G"] }] });
|
|
742
|
+
assert.equal(await readFile(file, "utf8"), "A\nX\nb\nD\ne\nG\n");
|
|
743
|
+
}));
|
|
744
|
+
|
|
745
|
+
test("unique candidate content is independent of oversized neighboring rows", async () => withDir(async (dir) => {
|
|
746
|
+
const original = "header\ntarget\ntail\n";
|
|
747
|
+
const before = `header\n${"x".repeat(17000)}\ntarget\ntail\n`;
|
|
748
|
+
const file = join(dir, "fallback.txt");
|
|
749
|
+
await writeFile(file, before);
|
|
750
|
+
let candidate = "";
|
|
751
|
+
await assert.rejects(call(makeEditOverride(dir), { path: file, edits: [
|
|
752
|
+
{ op: "replace", anchor: h(original, 2), body: ["updated"] },
|
|
753
|
+
] }), (error: Error) => {
|
|
754
|
+
candidate = anchorLine(error.message, 3);
|
|
755
|
+
assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
|
|
756
|
+
assert.doesNotMatch(error.message, /neighborhoods|truncated/);
|
|
757
|
+
assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
|
|
758
|
+
return true;
|
|
759
|
+
});
|
|
760
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
761
|
+
await call(makeEditOverride(dir), { path: file, edits: [{ op: "replace", anchor: candidate, body: ["updated"] }] });
|
|
762
|
+
assert.equal(await readFile(file, "utf8"), before.replace("target", "updated"));
|
|
763
|
+
}));
|
|
764
|
+
|
|
765
|
+
test("standalone CR replacements remain visible in diffs and exact in patches", async () => withDir(async (dir) => {
|
|
766
|
+
const file = join(dir, "cr.txt");
|
|
767
|
+
for (const [before, find, replacement] of [
|
|
768
|
+
["a\rb\n", "\r", "\n"],
|
|
769
|
+
["a\rb\n", "\r", "␍"],
|
|
770
|
+
]) {
|
|
771
|
+
await writeFile(file, before);
|
|
772
|
+
const result = await call(makeReplaceTool(dir), { path: file, find, replace: replacement, regex: true });
|
|
773
|
+
assert.equal(await readFile(file, "utf8"), before.replaceAll(find, replacement));
|
|
774
|
+
assert.equal(result.details.firstChangedLine, 1);
|
|
775
|
+
assert.match(result.details.diff, /^-1 a␍/m);
|
|
776
|
+
assert.match(result.details.diff, /^\+1 a/m);
|
|
777
|
+
assert.ok(!result.details.diff.includes("\r"));
|
|
778
|
+
assert.ok(result.details.patch.includes(`-a${before.includes("\r\n") ? "\r\n" : "\rb\n"}`));
|
|
779
|
+
assert.match(result.details.patch, /@@/);
|
|
780
|
+
}
|
|
781
|
+
}));
|
|
782
|
+
|
|
783
|
+
test("deletion successors and unique candidate rows display CR without altering anchors", async () => withDir(async (dir) => {
|
|
784
|
+
const file = join(dir, "cr.txt");
|
|
785
|
+
const before = "remove\na\rb\n";
|
|
786
|
+
await writeFile(file, before);
|
|
787
|
+
const result = await call(makeEditOverride(dir), { path: file, edits: [{ op: "delete", anchor: h(before, 1) }] });
|
|
788
|
+
assert.ok(result.content[0].text.includes(`${h("a\rb\n", 1)}│a␍b`));
|
|
789
|
+
assert.equal(await readFile(file, "utf8"), "a\rb\n");
|
|
790
|
+
await assert.rejects(call(makeEditOverride(dir), { path: file, edits: [{ op: "delete", anchor: h(before, 2) }] }), (error: Error) => {
|
|
791
|
+
assert.ok(error.message.includes(`${h("a\rb\n", 1)}│a␍b`));
|
|
792
|
+
assert.ok(!error.message.includes("\r"));
|
|
793
|
+
return true;
|
|
794
|
+
});
|
|
795
|
+
}));
|