@criogaid/pi-hashline-edit 0.3.1 → 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.
Files changed (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -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. Legacy oldText/newText is not accepted — the
9
- * schema requires an `op` discriminator, so legacy payloads are rejected at the
10
- * schema layer (a visible failure, never a silent degradation).
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 { truncateHead, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
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, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
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 type { ApplyFailure, Edit } from "../core/types.ts";
29
- import { canonicalPath } from "./path.ts";
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 { 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";
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
- const bounded = truncateHead(message, { maxBytes: 16 * 1024 - Buffer.byteLength(notice) });
39
- return bounded.content + (bounded.truncated ? notice : "");
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 anchorRef(description: string) {
44
- return Type.Optional(Type.String({ pattern: ANCHOR_PATTERN, description }));
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
- if (value === undefined) return undefined;
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
- const editOpSchema = Type.Object({
58
- op: Type.Union(
59
- [
60
- Type.Literal("replace", { description: "Replace the cited line(s) with `body`." }),
61
- Type.Literal("delete", { description: "Delete the cited line(s)." }),
62
- Type.Literal("insert_after", {
63
- description: "Insert `body` immediately after the anchor line — the anchor line is kept as-is; do NOT copy it into `body`.",
64
- }),
65
- Type.Literal("insert_before", {
66
- description: "Insert `body` immediately before the anchor line — the anchor line is kept as-is; do NOT copy it into `body`.",
67
- }),
68
- Type.Literal("append", { description: "Append `body` at the end of the file." }),
69
- Type.Literal("prepend", { description: "Prepend `body` at the start of the file." }),
70
- ],
71
- { description: "Operation kind" },
72
- ),
73
- anchor: anchorRef(
74
- 'Copy "LINE#HASH" from the latest read, grep, or mutation result. Required for replace/delete/insert; omit for append/prepend.',
75
- ),
76
- end: anchorRef(
77
- 'Inclusive last "LINE#HASH" for replace/delete ranges. Required to change multiple existing lines; omitted means only the anchor line. Omit for insert/append/prepend.',
78
- ),
79
- body: Type.Optional(Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), { description: "New content lines (required for replace/insert/append/prepend; each element must be one logical line without CR/LF; omit for delete)" })),
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
- return Type.Object({
84
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
85
- edits: Type.Array(editOpSchema, { description: "Hashline ops, each referencing LINE#HASH anchors from your latest read or edit result" }),
86
- ...(actionFusion ? { then_run: createThenRunSchema("Command to run after the edit succeeds; failure does not roll back the edit.") } : {}),
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
- const editSchema = createEditSchema(false);
91
- type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: ThenRunInput };
159
+ type EditOpInput = Static<EditSchema>["edits"][number];
92
160
 
93
- type EditOpInput = Static<typeof editOpSchema>;
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
- failure: ApplyFailure,
98
- snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
99
- candidateLines: ReadonlySet<number>,
206
+ failure: ApplyFailure,
207
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
208
+ candidateLines: ReadonlySet<number>,
100
209
  ): string {
101
- if (failure.kind !== "anchor") return failure.message;
210
+ if (failure.kind !== "anchor") return failure.message;
102
211
 
103
- const lines: string[] = [];
104
- const currentLines = splitLines(snapshot.currentText);
105
- const shownCandidates = new Set(candidateLines);
106
- let found = 0;
107
- let ambiguous = 0;
108
- let none = 0;
109
- for (const f of failure.failures) {
110
- if (f.recovery.kind === "found") found++;
111
- else if (f.recovery.kind === "ambiguous") ambiguous++;
112
- else none++;
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.";
116
- switch (f.recovery.kind) {
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);
131
- break;
132
- }
133
- case "ambiguous": {
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}`);
137
- break;
138
- }
139
- case "none":
140
- lines.push(
141
- `• ${where}: no checksum-matching candidate found. Use read to inspect the current file before retrying.` +
142
- (f.current === null ? " Cited line is out of range." : ""),
143
- );
144
- break;
145
- }
146
- }
147
- const parts: string[] = [];
148
- if (found) parts.push(`${found} shifted`);
149
- if (ambiguous) parts.push(`${ambiguous} ambiguous`);
150
- if (none) parts.push(`${none} unresolved`);
151
- const message = [
152
- `Anchor mismatch: ${parts.join(", ")}.`,
153
- "No changes written by this edit batch.",
154
- ...lines,
155
- ].join("\n");
156
- return boundDiagnostic(message, "\nDiagnostic output truncated at 16 KiB.");
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
- 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.");
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
- failure: ApplyFailure,
174
- snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
314
+ failure: ApplyFailure,
315
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
316
+ isBatch: boolean,
175
317
  ): 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}`;
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 JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
185
- function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } | { ok: false; error: string } {
186
- const edits: Edit[] = [];
187
- for (const o of ops) {
188
- const anchor = parseAnchor(o.anchor);
189
- const end = parseAnchor(o.end);
190
- if (o.op !== "replace" && o.op !== "delete" && end) return { ok: false, error: `${o.op} does not accept \`end\`` };
191
- if ((o.op === "append" || o.op === "prepend") && anchor) return { ok: false, error: `${o.op} does not accept \`anchor\`` };
192
- if (o.op === "delete" && o.body !== undefined) return { ok: false, error: "delete does not accept `body`" };
193
- switch (o.op) {
194
- case "replace":
195
- if (!anchor) return { ok: false, error: 'replace needs `anchor` "LINE#HASH"' };
196
- if (!o.body) return { ok: false, error: "replace needs `body`" };
197
- edits.push({ op: "replace", start: anchor, end, body: o.body });
198
- break;
199
- case "delete":
200
- if (!anchor) return { ok: false, error: 'delete needs `anchor` "LINE#HASH"' };
201
- edits.push({ op: "delete", start: anchor, end });
202
- break;
203
- case "insert_after":
204
- case "insert_before":
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(before: string, newText: string, touched: readonly number[], contextLines: readonly number[], anchors: AnchorFormatter): string {
224
- const idxs = [...new Set(touched)].sort((a, b) => a - b);
225
- return formatMutationAnchors(splitLines(before), splitLines(newText), idxs, anchors, "Updated anchors:", new Set(contextLines));
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: any, theme: any, counts?: DiffCounts): string {
230
- let t = theme.fg("toolTitle", theme.bold("edit "));
231
- t += theme.fg("accent", args.path);
232
- const n = args.edits?.length ?? 0;
233
- if (n) t += theme.fg("dim", ` — ${n} op${n > 1 ? "s" : ""}: ${args.edits[0].op}`);
234
- if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
235
- return t;
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?: ReturnType<typeof createActionFusionExecutor>): any {
239
- const parameters = createEditSchema(fusion !== undefined);
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
- return {
242
- name: "edit" as const,
243
- label: "edit",
244
- description:
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.",
246
- promptSnippet: "Edit file lines using verified anchors",
247
- promptGuidelines: [
248
- "Batch changes to the same file in one edit call.",
249
- "Reuse prior anchors when their line number and content are unchanged. Re-read changed or shifted lines when no fresh anchor is available.",
250
- ...(fusion ? ACTION_FUSION_GUIDELINES : []),
251
- ],
252
- parameters,
253
- renderShell: "default" as const,
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
- renderCall(args: EditParams, theme: any, context: any) {
256
- return renderMutationCall(args, theme, context, editHeader);
257
- },
420
+ renderCall(args: EditParams, theme: Theme, context: EditRenderContext) {
421
+ return renderMutationCall(args, theme, context, editHeader);
422
+ },
258
423
 
259
- renderResult(result: any, options: any, theme: any, context: any) {
260
- return renderMutationResult(result, options, theme, context, "Editing…", "Edited", editHeader);
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
- async execute(toolCallId: string, params: EditParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
264
- const { then_run, ...mutationParams } = params;
265
- if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
266
- const absolutePath = canonicalPath(cwd, mutationParams.path);
267
- let mutationAnchors = "";
268
- const mutate = () => {
269
- const path = mutationParams.path;
270
- if (!mutationParams.edits?.length) throw new Error(`Edit ${path}: \`edits\` is empty or missing.`);
271
- return withFileMutationQueue(absolutePath, () => runHashline(
272
- absolutePath,
273
- path,
274
- mutationParams.edits,
275
- signal,
276
- (anchors) => { mutationAnchors = anchors; },
277
- ));
278
- };
279
- const finalizeMutation = (result: any, publishAnchors: boolean) => appendMutationAnchors(result, mutationAnchors, publishAnchors);
280
- if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
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
- async function runHashline(
296
- absPath: string,
297
- displayPath: string,
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
- // 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);
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
- // Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
321
- if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before write.`);
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
- 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,
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
  }