@criogaid/pi-hashline-edit 0.3.0 → 0.4.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 +59 -50
- package/package.json +8 -3
- package/src/core/apply.test.ts +366 -310
- package/src/core/apply.ts +269 -202
- package/src/core/hash.test.ts +61 -23
- package/src/core/hash.ts +45 -16
- package/src/core/lines.test.ts +46 -27
- package/src/core/lines.ts +36 -28
- package/src/core/ranges.test.ts +73 -19
- package/src/core/ranges.ts +15 -15
- package/src/core/text.test.ts +3 -3
- package/src/core/text.ts +28 -9
- package/src/core/types.ts +54 -36
- package/src/index.ts +22 -16
- package/src/integration/grep-rg.test.ts +834 -219
- package/src/integration/large-text.test.ts +62 -0
- package/src/integration/replace-package.test.ts +37 -0
- package/src/pi/action-fusion.test.ts +535 -206
- package/src/pi/action-fusion.ts +469 -244
- package/src/pi/anchor-format.test.ts +30 -19
- package/src/pi/anchor-format.ts +27 -14
- package/src/pi/budgets.ts +20 -0
- package/src/pi/config.test.ts +60 -30
- package/src/pi/config.ts +45 -32
- package/src/pi/directory-sync.test.ts +55 -0
- package/src/pi/e2e-scenarios.test.ts +359 -0
- package/src/pi/edit-tool.ts +426 -262
- package/src/pi/error-text.ts +21 -0
- package/src/pi/execute.test.ts +1594 -694
- package/src/pi/failure-context.test.ts +105 -83
- package/src/pi/failure-context.ts +83 -71
- package/src/pi/failure-path.test.ts +171 -64
- package/src/pi/file-commit.test.ts +446 -233
- package/src/pi/file-commit.ts +347 -203
- package/src/pi/fusion-card.test.ts +118 -83
- package/src/pi/fusion-card.ts +120 -85
- package/src/pi/grep-output.ts +208 -0
- package/src/pi/grep-render.ts +58 -0
- package/src/pi/grep-scope.ts +152 -0
- package/src/pi/grep-search.ts +217 -0
- package/src/pi/grep-tool.ts +191 -766
- package/src/pi/grep.test.ts +562 -150
- package/src/pi/mutation-result.test.ts +37 -0
- package/src/pi/mutation-result.ts +107 -59
- package/src/pi/mutation-runner.ts +168 -0
- package/src/pi/path.ts +20 -12
- package/src/pi/pi.test.ts +95 -52
- package/src/pi/read-tool.ts +219 -130
- package/src/pi/registration.test.ts +274 -113
- package/src/pi/render.test.ts +218 -83
- package/src/pi/render.ts +152 -95
- package/src/pi/replace-apply.ts +109 -0
- package/src/pi/replace-tool.ts +280 -240
- package/src/pi/replace-worker.mjs +4 -0
- package/src/pi/replace-worker.ts +10 -0
- package/src/pi/replace.test.ts +773 -389
- package/src/pi/result-safety.test.ts +779 -342
- package/src/pi/rg-line-filter.test.ts +64 -36
- package/src/pi/rg-line-filter.ts +40 -124
- package/src/pi/rg-line-ranges.test.ts +57 -31
- package/src/pi/rg-line-ranges.ts +44 -82
- package/src/pi/rg-text-view.ts +106 -36
- package/src/pi/schema.ts +27 -0
- package/src/pi/state.ts +7 -7
- package/src/pi/text-stream.test.ts +118 -0
- package/src/pi/text-stream.ts +136 -0
- package/src/pi/tool-call.testing.ts +37 -0
- package/src/pi/write-tool.ts +115 -52
- package/src/pi/write.test.ts +248 -96
package/src/pi/edit-tool.ts
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* (or from a prior edit's "Updated anchors"). The core verifies each anchor live against
|
|
6
6
|
* the current file content — no snapshot, no global stale check: a cited line
|
|
7
7
|
* that changed (or was misremembered) fails its own anchor; unchanged lines
|
|
8
|
-
* elsewhere never block the edit.
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* elsewhere never block the edit. The extension requires structured `edits` arrays
|
|
9
|
+
* at execution; Pi may coerce a single object before validation. Legacy
|
|
10
|
+
* oldText/newText inputs fail schema validation before mutation.
|
|
11
11
|
*
|
|
12
12
|
* On success the result carries fresh `LINE#HASH` anchors for the lines this
|
|
13
13
|
* edit produced (and the line that shifted into a deletion gap), so the model
|
|
@@ -19,314 +19,478 @@
|
|
|
19
19
|
* @module pi-hashline-edit/pi
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
truncateHead,
|
|
24
|
+
type ExtensionContext,
|
|
25
|
+
type Theme,
|
|
26
|
+
type ToolDefinition,
|
|
27
|
+
type ToolRenderResultOptions,
|
|
28
|
+
} from "@earendil-works/pi-coding-agent";
|
|
29
|
+
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
23
30
|
import { Type, type Static } from "typebox";
|
|
24
|
-
import { ACTION_FUSION_GUIDELINES,
|
|
25
|
-
import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
|
|
31
|
+
import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
26
32
|
import { applyEdits } from "../core/index.ts";
|
|
27
33
|
import { splitLines } from "../core/lines.ts";
|
|
28
|
-
import
|
|
29
|
-
import {
|
|
34
|
+
import { unwritableTextReason } from "../core/text.ts";
|
|
35
|
+
import { invalidArgument } from "./error-text.ts";
|
|
36
|
+
import type { Anchor, ApplyFailure, Edit } from "../core/types.ts";
|
|
30
37
|
import { getState } from "./state.ts";
|
|
31
|
-
import {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
38
|
+
import {
|
|
39
|
+
anchorPattern,
|
|
40
|
+
createAnchorFormatter,
|
|
41
|
+
parseAnchorToken,
|
|
42
|
+
type AnchorFormatter,
|
|
43
|
+
} from "./anchor-format.ts";
|
|
44
|
+
import {
|
|
45
|
+
formatDiffCounts,
|
|
46
|
+
renderMutationCall,
|
|
47
|
+
renderMutationResult,
|
|
48
|
+
type DiffCounts,
|
|
49
|
+
} from "./render.ts";
|
|
50
|
+
import {
|
|
51
|
+
formatAmbiguousCandidateNeighborhoods,
|
|
52
|
+
MAX_AMBIGUOUS_CANDIDATES,
|
|
53
|
+
} from "./failure-context.ts";
|
|
54
|
+
import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
|
|
55
|
+
import { formatMutationAnchors } from "./mutation-result.ts";
|
|
56
|
+
import {
|
|
57
|
+
executeMutation,
|
|
58
|
+
runTextMutation,
|
|
59
|
+
type ActionFusionExecutor,
|
|
60
|
+
type MutationTarget,
|
|
61
|
+
type TextMutationDetails,
|
|
62
|
+
} from "./mutation-runner.ts";
|
|
63
|
+
type EditDetails = TextMutationDetails;
|
|
64
|
+
type EditRenderContext = Parameters<NonNullable<ToolDefinition<EditSchema>["renderCall"]>>[2];
|
|
35
65
|
|
|
36
66
|
/** Keep independent byte budgets for failure details and input-anchor checks. */
|
|
37
67
|
function boundDiagnostic(message: string, notice: string): string {
|
|
38
|
-
|
|
39
|
-
|
|
68
|
+
const bounded = truncateHead(message, { maxBytes: MAX_BLOCK_BYTES - Buffer.byteLength(notice) });
|
|
69
|
+
return bounded.content + (bounded.truncated ? notice : "");
|
|
40
70
|
}
|
|
41
71
|
|
|
42
|
-
|
|
43
|
-
function
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Parse copied tokens at the boundary; core edits retain numeric anchors. */
|
|
72
|
+
/** Split a validated anchor token; prepareArguments and the schema already checked it. */
|
|
73
|
+
function parseAnchor(value: string): Anchor;
|
|
74
|
+
function parseAnchor(value: string | undefined): Anchor | undefined;
|
|
48
75
|
function parseAnchor(value: string | undefined) {
|
|
49
|
-
|
|
50
|
-
const match = typeof value === "string" ? new RegExp(ANCHOR_PATTERN).exec(value) : null;
|
|
51
|
-
if (!match || !Number.isSafeInteger(Number(match[1]))) {
|
|
52
|
-
throw new Error('Invalid anchor; copy a complete "LINE#HASH" token from the latest tool result.');
|
|
53
|
-
}
|
|
54
|
-
return { line: Number(match[1]), hash: match[2] };
|
|
76
|
+
return value === undefined ? undefined : parseAnchorToken(value)!;
|
|
55
77
|
}
|
|
56
78
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
79
|
+
/** Edit parameters; anchors must carry exactly `hashLen` hash characters. */
|
|
80
|
+
function buildEditSchema(hashLen: number) {
|
|
81
|
+
const pattern = anchorPattern(hashLen);
|
|
82
|
+
const requiredAnchor = Type.String({
|
|
83
|
+
pattern,
|
|
84
|
+
description: "LINE#HASH of the target line.",
|
|
85
|
+
});
|
|
86
|
+
const optionalEnd = Type.Optional(
|
|
87
|
+
Type.String({
|
|
88
|
+
pattern,
|
|
89
|
+
description: "Inclusive last LINE#HASH of the range; omit for one line.",
|
|
90
|
+
}),
|
|
91
|
+
);
|
|
92
|
+
const bodyLines = Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
|
|
93
|
+
description: "New lines, one per element, without CR/LF.",
|
|
94
|
+
});
|
|
95
|
+
const editOpSchema = Type.Union([
|
|
96
|
+
Type.Object(
|
|
97
|
+
{
|
|
98
|
+
op: Type.Literal("replace", { description: "Replace the cited line(s) with `body`." }),
|
|
99
|
+
anchor: requiredAnchor,
|
|
100
|
+
end: optionalEnd,
|
|
101
|
+
body: bodyLines,
|
|
102
|
+
},
|
|
103
|
+
{ additionalProperties: false },
|
|
104
|
+
),
|
|
105
|
+
Type.Object(
|
|
106
|
+
{
|
|
107
|
+
op: Type.Literal("delete", { description: "Delete the cited line(s)." }),
|
|
108
|
+
anchor: requiredAnchor,
|
|
109
|
+
end: optionalEnd,
|
|
110
|
+
},
|
|
111
|
+
{ additionalProperties: false },
|
|
112
|
+
),
|
|
113
|
+
Type.Object(
|
|
114
|
+
{
|
|
115
|
+
op: Type.Union([Type.Literal("insert_after"), Type.Literal("insert_before")], {
|
|
116
|
+
description:
|
|
117
|
+
"Insert body beside the anchor line, which is kept; do not repeat it in body.",
|
|
118
|
+
}),
|
|
119
|
+
anchor: requiredAnchor,
|
|
120
|
+
body: bodyLines,
|
|
121
|
+
},
|
|
122
|
+
{ additionalProperties: false },
|
|
123
|
+
),
|
|
124
|
+
Type.Object(
|
|
125
|
+
{
|
|
126
|
+
op: Type.Union([Type.Literal("append"), Type.Literal("prepend")], {
|
|
127
|
+
description: "Add body at the end or start of the file.",
|
|
128
|
+
}),
|
|
129
|
+
body: bodyLines,
|
|
130
|
+
},
|
|
131
|
+
{ additionalProperties: false },
|
|
132
|
+
),
|
|
133
|
+
]);
|
|
134
|
+
return Type.Object(
|
|
135
|
+
{
|
|
136
|
+
path: Type.String({
|
|
137
|
+
minLength: 1,
|
|
138
|
+
description: "Path to the file (relative or absolute)",
|
|
139
|
+
}),
|
|
140
|
+
edits: Type.Array(editOpSchema, {
|
|
141
|
+
minItems: 1,
|
|
142
|
+
description: `Operations on one snapshot. Anchors are LINE#HASH with exactly ${hashLen} hash characters, copied from the latest read, grep, edit, or replace result.`,
|
|
143
|
+
}),
|
|
144
|
+
},
|
|
145
|
+
{ additionalProperties: false },
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
type EditSchema = ReturnType<typeof buildEditSchema>;
|
|
81
149
|
|
|
82
|
-
function createEditSchema(actionFusion: boolean) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
150
|
+
function createEditSchema(actionFusion: boolean, hashLen: number) {
|
|
151
|
+
return withThenRunSchema(
|
|
152
|
+
buildEditSchema(hashLen),
|
|
153
|
+
"Command to run after the edit succeeds; failure does not roll back the edit.",
|
|
154
|
+
actionFusion,
|
|
155
|
+
);
|
|
88
156
|
}
|
|
157
|
+
type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
|
|
89
158
|
|
|
90
|
-
|
|
91
|
-
type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: ThenRunInput };
|
|
159
|
+
type EditOpInput = Static<EditSchema>["edits"][number];
|
|
92
160
|
|
|
93
|
-
|
|
161
|
+
/**
|
|
162
|
+
* Checks the schema cannot express, run before Pi's schema validation. Rejects body
|
|
163
|
+
* lines that cannot be written as UTF-8, anchor line numbers beyond the safe-integer
|
|
164
|
+
* range, and names anchors whose hash length differs from `hashLen` (the schema would
|
|
165
|
+
* report only a bare pattern mismatch). Malformed shapes are left to the schema.
|
|
166
|
+
* Arguments are never changed.
|
|
167
|
+
*/
|
|
168
|
+
function checkEditArguments(args: unknown, hashLen: number): void {
|
|
169
|
+
const edits = (args as { edits?: unknown } | null)?.edits;
|
|
170
|
+
if (!Array.isArray(edits)) return;
|
|
171
|
+
const mismatches: string[] = [];
|
|
172
|
+
edits.forEach((op, index) => {
|
|
173
|
+
const body = (op as Record<string, unknown> | null)?.body;
|
|
174
|
+
if (Array.isArray(body)) {
|
|
175
|
+
body.forEach((line, lineIndex) => {
|
|
176
|
+
const reason = typeof line === "string" ? unwritableTextReason(line) : undefined;
|
|
177
|
+
if (reason) throw invalidArgument(`edits[${index}].body[${lineIndex}]`, reason);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
for (const field of ["anchor", "end"] as const) {
|
|
181
|
+
const value = (op as Record<string, unknown> | null)?.[field];
|
|
182
|
+
if (typeof value !== "string") continue;
|
|
183
|
+
const token = parseAnchorToken(value);
|
|
184
|
+
if (token && !Number.isSafeInteger(token.line)) {
|
|
185
|
+
throw invalidArgument(
|
|
186
|
+
`edits[${index}].${field}`,
|
|
187
|
+
`line number in ${value} exceeds the safe integer range; copy a complete "LINE#HASH" token from the latest tool result.`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
if (token && token.hash.length !== hashLen) {
|
|
191
|
+
mismatches.push(
|
|
192
|
+
`edits[${index}].${field} ${value} has ${token.hash.length} hash characters`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
if (mismatches.length) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`Anchor hash length mismatch: ${mismatches.join("; ")}, but hashLen is ${hashLen}. Anchors from a different hashLen setting cannot be verified; read or grep the file for current anchors.`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
94
203
|
|
|
95
204
|
/** Format failure mappings and complete unique-candidate rows within the detail budget. */
|
|
96
205
|
function formatFailureDetails(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
206
|
+
failure: ApplyFailure,
|
|
207
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
208
|
+
candidateLines: ReadonlySet<number>,
|
|
100
209
|
): string {
|
|
101
|
-
|
|
210
|
+
if (failure.kind !== "anchor") return failure.message;
|
|
102
211
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
212
|
+
const lines: string[] = [];
|
|
213
|
+
const currentLines = splitLines(snapshot.currentText);
|
|
214
|
+
const shownCandidates = new Set(candidateLines);
|
|
215
|
+
let found = 0;
|
|
216
|
+
let ambiguous = 0;
|
|
217
|
+
let none = 0;
|
|
218
|
+
for (const f of failure.failures) {
|
|
219
|
+
if (f.recovery.kind === "found") found++;
|
|
220
|
+
else if (f.recovery.kind === "ambiguous") ambiguous++;
|
|
221
|
+
else none++;
|
|
222
|
+
const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
|
|
223
|
+
const search =
|
|
224
|
+
f.recovery.kind === "none"
|
|
225
|
+
? ""
|
|
226
|
+
: f.recovery.scope === "local"
|
|
227
|
+
? "Search: local; matches outside the window were not checked."
|
|
228
|
+
: "Search: full file.";
|
|
229
|
+
switch (f.recovery.kind) {
|
|
230
|
+
case "found": {
|
|
231
|
+
const content = currentLines[f.recovery.newLine - 1];
|
|
232
|
+
const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
|
|
233
|
+
const row =
|
|
234
|
+
content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
|
|
235
|
+
let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
|
|
236
|
+
if (!shownCandidates.has(f.recovery.newLine)) {
|
|
237
|
+
if (
|
|
238
|
+
content !== undefined &&
|
|
239
|
+
Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES
|
|
240
|
+
) {
|
|
241
|
+
detail += `\n${row}`;
|
|
242
|
+
shownCandidates.add(f.recovery.newLine);
|
|
243
|
+
} else {
|
|
244
|
+
detail += ` Candidate content exceeds ${MAX_RECOVERY_CANDIDATE_BYTES} bytes.`;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
lines.push(detail);
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
case "ambiguous": {
|
|
251
|
+
const list = f.recovery.candidates
|
|
252
|
+
.slice(0, MAX_AMBIGUOUS_CANDIDATES)
|
|
253
|
+
.map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`)
|
|
254
|
+
.join(" / ");
|
|
255
|
+
const more =
|
|
256
|
+
f.recovery.candidates.length > MAX_AMBIGUOUS_CANDIDATES
|
|
257
|
+
? ` (${f.recovery.candidates.length - MAX_AMBIGUOUS_CANDIDATES} more candidates omitted)`
|
|
258
|
+
: "";
|
|
259
|
+
lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
case "none": {
|
|
263
|
+
const row =
|
|
264
|
+
f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
|
|
265
|
+
if (row !== null && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
|
|
266
|
+
lines.push(
|
|
267
|
+
`• ${where}: no checksum-matching candidate found. Current cited line (validation snapshot; observation only):\n${row}\nConfirm this is the intended target before reusing its anchor directly; retries revalidate.`,
|
|
268
|
+
);
|
|
269
|
+
} else {
|
|
270
|
+
lines.push(
|
|
271
|
+
`• ${where}: no checksum-matching candidate found. Use read or grep to inspect the current file before retrying.` +
|
|
272
|
+
(f.current === null
|
|
273
|
+
? " Cited line is out of range."
|
|
274
|
+
: ` Current row exceeds ${MAX_RECOVERY_CANDIDATE_BYTES} bytes.`),
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const parts: string[] = [];
|
|
282
|
+
if (found) parts.push(`${found} shifted`);
|
|
283
|
+
if (ambiguous) parts.push(`${ambiguous} ambiguous`);
|
|
284
|
+
if (none) parts.push(`${none} unresolved`);
|
|
285
|
+
const message = [
|
|
286
|
+
`Anchor mismatch: ${parts.join(", ")}.`,
|
|
287
|
+
"No changes written by this edit batch.",
|
|
288
|
+
...lines,
|
|
289
|
+
].join("\n");
|
|
290
|
+
return boundDiagnostic(
|
|
291
|
+
message,
|
|
292
|
+
`\nDiagnostic output truncated at ${formatKiB(MAX_BLOCK_BYTES)}.`,
|
|
293
|
+
);
|
|
157
294
|
}
|
|
158
295
|
|
|
159
296
|
function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
297
|
+
const rows = failure.checks.map(
|
|
298
|
+
(check) =>
|
|
299
|
+
`op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
|
|
300
|
+
);
|
|
301
|
+
const message = [
|
|
302
|
+
"Input-anchor checks (this snapshot):",
|
|
303
|
+
...rows,
|
|
304
|
+
"Anchor checks only; retries revalidate.",
|
|
305
|
+
].join("\n");
|
|
306
|
+
return boundDiagnostic(
|
|
307
|
+
message,
|
|
308
|
+
`\nAnchor-check output truncated at ${formatKiB(MAX_BLOCK_BYTES)}; omitted entries are not implied matched.`,
|
|
309
|
+
);
|
|
169
310
|
}
|
|
170
311
|
|
|
171
312
|
/** Keep validation status and observation context visible even when failure details are truncated. */
|
|
172
313
|
function formatFailure(
|
|
173
|
-
|
|
174
|
-
|
|
314
|
+
failure: ApplyFailure,
|
|
315
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
316
|
+
isBatch: boolean,
|
|
175
317
|
): string {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
318
|
+
const candidateNeighborhoods =
|
|
319
|
+
failure.kind === "anchor"
|
|
320
|
+
? formatAmbiguousCandidateNeighborhoods(
|
|
321
|
+
snapshot.currentText,
|
|
322
|
+
failure.failures,
|
|
323
|
+
snapshot.anchors,
|
|
324
|
+
)
|
|
325
|
+
: { text: "", shownLines: new Set<number>() };
|
|
326
|
+
const guidance =
|
|
327
|
+
failure.kind === "anchor"
|
|
328
|
+
? "\nCheck the intended target before retrying; use read or grep for omitted or additional context."
|
|
329
|
+
: "";
|
|
330
|
+
const anchorChecks =
|
|
331
|
+
isBatch && failure.checks.length > 0
|
|
332
|
+
? `\n${formatAnchorChecks(failure, snapshot.anchors)}`
|
|
333
|
+
: "";
|
|
334
|
+
return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}${anchorChecks}${candidateNeighborhoods.text}${guidance}`;
|
|
182
335
|
}
|
|
183
336
|
|
|
184
|
-
/** Translate
|
|
185
|
-
function toCoreEdits(ops: readonly EditOpInput[]):
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (!anchor) return { ok: false, error: `${o.op} needs \`anchor\` "LINE#HASH"` };
|
|
206
|
-
if (!o.body) return { ok: false, error: `${o.op} needs \`body\`` };
|
|
207
|
-
edits.push({ op: o.op, anchor, body: o.body });
|
|
208
|
-
break;
|
|
209
|
-
case "append":
|
|
210
|
-
case "prepend":
|
|
211
|
-
if (!o.body) return { ok: false, error: `${o.op} needs \`body\`` };
|
|
212
|
-
edits.push({ op: o.op, body: o.body });
|
|
213
|
-
break;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
return { ok: true, edits };
|
|
337
|
+
/** Translate validated public operations into core edits, parsing numeric anchor positions. */
|
|
338
|
+
function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
|
|
339
|
+
return ops.map((op) => {
|
|
340
|
+
switch (op.op) {
|
|
341
|
+
case "replace":
|
|
342
|
+
return {
|
|
343
|
+
op: "replace",
|
|
344
|
+
start: parseAnchor(op.anchor),
|
|
345
|
+
end: parseAnchor(op.end),
|
|
346
|
+
body: op.body,
|
|
347
|
+
};
|
|
348
|
+
case "delete":
|
|
349
|
+
return { op: "delete", start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
|
|
350
|
+
case "insert_after":
|
|
351
|
+
case "insert_before":
|
|
352
|
+
return { op: op.op, anchor: parseAnchor(op.anchor), body: op.body };
|
|
353
|
+
case "append":
|
|
354
|
+
case "prepend":
|
|
355
|
+
return { op: op.op, body: op.body };
|
|
356
|
+
}
|
|
357
|
+
});
|
|
217
358
|
}
|
|
218
359
|
|
|
219
360
|
/**
|
|
220
361
|
* Return compact tokens for changed caller-supplied rows, retaining content for deletion successors.
|
|
221
362
|
* Uses the applicator's final indices so mixed batches do not need a second position calculation.
|
|
222
363
|
*/
|
|
223
|
-
function formatUpdatedAnchors(
|
|
224
|
-
|
|
225
|
-
|
|
364
|
+
function formatUpdatedAnchors(
|
|
365
|
+
before: string,
|
|
366
|
+
newText: string,
|
|
367
|
+
touched: readonly number[],
|
|
368
|
+
contextLines: readonly number[],
|
|
369
|
+
anchors: AnchorFormatter,
|
|
370
|
+
): string {
|
|
371
|
+
const idxs = [...new Set(touched)].sort((a, b) => a - b);
|
|
372
|
+
return formatMutationAnchors(
|
|
373
|
+
splitLines(before),
|
|
374
|
+
splitLines(newText),
|
|
375
|
+
idxs,
|
|
376
|
+
anchors,
|
|
377
|
+
"Updated anchors:",
|
|
378
|
+
new Set(contextLines),
|
|
379
|
+
);
|
|
226
380
|
}
|
|
227
381
|
|
|
228
382
|
/** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
|
|
229
|
-
function editHeader(args:
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
383
|
+
function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
|
|
384
|
+
let t = theme.fg("toolTitle", theme.bold("edit "));
|
|
385
|
+
t += theme.fg("accent", args.path);
|
|
386
|
+
const edits = Array.isArray(args.edits) ? args.edits : [];
|
|
387
|
+
const n = edits.length;
|
|
388
|
+
if (n) {
|
|
389
|
+
const kind = typeof edits[0]?.op === "string" ? edits[0].op : "unknown";
|
|
390
|
+
t += theme.fg("dim", ` — ${n} op${n > 1 ? "s" : ""}: ${kind}`);
|
|
391
|
+
}
|
|
392
|
+
if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
|
|
393
|
+
return t;
|
|
236
394
|
}
|
|
237
395
|
|
|
238
|
-
export function makeEditOverride(cwd: string, fusion?:
|
|
239
|
-
|
|
396
|
+
export function makeEditOverride(cwd: string, fusion?: ActionFusionExecutor) {
|
|
397
|
+
// Schema, argument preparation, and verification share the hash length registered with the tool.
|
|
398
|
+
const { hashLen } = getState().config;
|
|
399
|
+
const parameters = createEditSchema(fusion !== undefined, hashLen);
|
|
240
400
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
401
|
+
return {
|
|
402
|
+
name: "edit" as const,
|
|
403
|
+
label: "edit",
|
|
404
|
+
description:
|
|
405
|
+
"Edit file lines by LINE#HASH anchors checked against the current file. Returns fresh anchors for changed lines. On anchor failure, shows current context and recovery candidates; nothing is retried automatically.",
|
|
406
|
+
promptSnippet: "Edit file lines using verified anchors",
|
|
407
|
+
promptGuidelines: [
|
|
408
|
+
"Batch related edits to one file in a single edit call; all its anchors are checked against one snapshot.",
|
|
409
|
+
"Reuse anchors while their line number and content are unchanged; inserts and deletes shift later lines, so use the edit's Updated anchors or re-read shifted lines.",
|
|
410
|
+
"On edit anchor failure, inspect the recovery candidates before retrying or re-reading.",
|
|
411
|
+
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
412
|
+
],
|
|
413
|
+
parameters,
|
|
414
|
+
prepareArguments(args: unknown): EditParams {
|
|
415
|
+
checkEditArguments(args, hashLen);
|
|
416
|
+
return args as EditParams;
|
|
417
|
+
},
|
|
418
|
+
renderShell: "default" as const,
|
|
254
419
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
420
|
+
renderCall(args: EditParams, theme: Theme, context: EditRenderContext) {
|
|
421
|
+
return renderMutationCall(args, theme, context, editHeader);
|
|
422
|
+
},
|
|
258
423
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
424
|
+
renderResult(
|
|
425
|
+
result: AgentToolResult<EditDetails>,
|
|
426
|
+
options: ToolRenderResultOptions,
|
|
427
|
+
theme: Theme,
|
|
428
|
+
context: EditRenderContext,
|
|
429
|
+
) {
|
|
430
|
+
return renderMutationResult(
|
|
431
|
+
result,
|
|
432
|
+
options,
|
|
433
|
+
theme,
|
|
434
|
+
context,
|
|
435
|
+
"Editing…",
|
|
436
|
+
"Edited",
|
|
437
|
+
editHeader,
|
|
438
|
+
);
|
|
439
|
+
},
|
|
262
440
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
return fusion({
|
|
282
|
-
toolCallId,
|
|
283
|
-
absolutePath,
|
|
284
|
-
thenRun: then_run,
|
|
285
|
-
mutate,
|
|
286
|
-
finalizeMutation,
|
|
287
|
-
signal,
|
|
288
|
-
ctx,
|
|
289
|
-
onUpdate,
|
|
290
|
-
});
|
|
291
|
-
},
|
|
292
|
-
};
|
|
441
|
+
async execute(
|
|
442
|
+
toolCallId: string,
|
|
443
|
+
params: EditParams,
|
|
444
|
+
signal: AbortSignal | undefined,
|
|
445
|
+
onUpdate: AgentToolUpdateCallback<EditDetails> | undefined,
|
|
446
|
+
ctx: ExtensionContext,
|
|
447
|
+
) {
|
|
448
|
+
return executeMutation<Omit<EditParams, "then_run">, EditDetails>(
|
|
449
|
+
{
|
|
450
|
+
cwd,
|
|
451
|
+
fusion,
|
|
452
|
+
reportsAnchors: true,
|
|
453
|
+
run: (mutationParams, target) => runHashline(target, mutationParams.edits, hashLen),
|
|
454
|
+
},
|
|
455
|
+
{ toolCallId, params, signal, onUpdate, ctx },
|
|
456
|
+
);
|
|
457
|
+
},
|
|
458
|
+
};
|
|
293
459
|
}
|
|
294
460
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
editOps: readonly EditOpInput[],
|
|
299
|
-
signal: AbortSignal | undefined,
|
|
300
|
-
onAnchors: (anchors: string) => void,
|
|
301
|
-
) {
|
|
302
|
-
const anchorFormatter = createAnchorFormatter();
|
|
303
|
-
const { shiftRadius } = getState().config;
|
|
304
|
-
|
|
305
|
-
const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
|
|
306
|
-
// Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
|
|
307
|
-
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before apply.`);
|
|
308
|
-
|
|
309
|
-
const translated = toCoreEdits(editOps);
|
|
310
|
-
if (!translated.ok) throw new Error(translated.error);
|
|
461
|
+
function runHashline(target: MutationTarget, editOps: readonly EditOpInput[], hashLen: number) {
|
|
462
|
+
const anchorFormatter = createAnchorFormatter(hashLen);
|
|
463
|
+
const { shiftRadius } = getState().config;
|
|
311
464
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
// candidates and resubmit with fresh anchors.
|
|
315
|
-
const result = applyEdits(currentText, translated.edits, anchorFormatter.hashLen, shiftRadius);
|
|
316
|
-
if (!result.ok) {
|
|
317
|
-
throw new Error(formatFailure(result.failure, { currentText, anchors: anchorFormatter }));
|
|
318
|
-
}
|
|
465
|
+
return runTextMutation("edit", target, (currentText) => {
|
|
466
|
+
const translated = toCoreEdits(editOps);
|
|
319
467
|
|
|
320
|
-
|
|
321
|
-
|
|
468
|
+
// Recovery reports checksum candidates from nearby lines, then the whole file
|
|
469
|
+
// if needed. Every failed anchor still rejects the batch; callers inspect
|
|
470
|
+
// candidates and resubmit with fresh anchors.
|
|
471
|
+
const result = applyEdits(currentText, translated, anchorFormatter.hashLen, shiftRadius);
|
|
472
|
+
if (!result.ok) {
|
|
473
|
+
throw new Error(
|
|
474
|
+
formatFailure(
|
|
475
|
+
result.failure,
|
|
476
|
+
{ currentText, anchors: anchorFormatter },
|
|
477
|
+
translated.length > 1,
|
|
478
|
+
),
|
|
479
|
+
);
|
|
480
|
+
}
|
|
322
481
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
482
|
+
return {
|
|
483
|
+
text: result.text,
|
|
484
|
+
anchors: () =>
|
|
485
|
+
formatUpdatedAnchors(
|
|
486
|
+
currentText,
|
|
487
|
+
result.text,
|
|
488
|
+
result.touchedLines,
|
|
489
|
+
result.contextLines,
|
|
490
|
+
anchorFormatter,
|
|
491
|
+
),
|
|
492
|
+
summary: () =>
|
|
493
|
+
`Edited ${target.displayPath} (${translated.length} op(s)${result.changed ? "" : ", no net change"}).`,
|
|
494
|
+
};
|
|
495
|
+
});
|
|
332
496
|
}
|