@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -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,342 @@
19
19
  * @module pi-hashline-edit/pi
20
20
  */
21
21
 
22
- import { truncateHead, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
22
+ import {
23
+ type ExtensionContext,
24
+ type Theme,
25
+ type ToolDefinition,
26
+ type ToolRenderResultOptions,
27
+ } from "@earendil-works/pi-coding-agent";
28
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
23
29
  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";
26
- import { applyEdits } from "../core/index.ts";
30
+ import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
31
+ import { applyEdits } from "../core/apply.ts";
27
32
  import { splitLines } from "../core/lines.ts";
28
- import type { ApplyFailure, Edit } from "../core/types.ts";
29
- import { canonicalPath } from "./path.ts";
30
- 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";
33
+ import { unwritableTextReason } from "../core/text.ts";
34
+ import { invalidArgument } from "./error-text.ts";
35
+ import type { Anchor, Edit } from "../core/types.ts";
36
+ import type { HashlineEditConfig } from "./config.ts";
37
+ import {
38
+ anchorPattern,
39
+ createAnchorFormatter,
40
+ parseAnchorToken,
41
+ type AnchorFormatter,
42
+ } from "./anchor-format.ts";
43
+ import {
44
+ formatDiffCounts,
45
+ renderMutationCall,
46
+ renderMutationResult,
47
+ type DiffCounts,
48
+ } from "./render.ts";
49
+ import { formatFailure } from "./failure-context.ts";
50
+ import { formatMutationAnchors } from "./mutation-result.ts";
51
+ import {
52
+ executeMutation,
53
+ runTextMutation,
54
+ type ActionFusionExecutor,
55
+ type MutationTarget,
56
+ type TextMutationDetails,
57
+ } from "./mutation-runner.ts";
58
+ type EditDetails = TextMutationDetails;
59
+ type EditRenderContext = Parameters<NonNullable<ToolDefinition<EditSchema>["renderCall"]>>[2];
35
60
 
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
- }
41
-
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. */
61
+ /** Split a validated anchor token; prepareArguments and the schema already checked it. */
62
+ function parseAnchor(value: string): Anchor;
63
+ function parseAnchor(value: string | undefined): Anchor | undefined;
48
64
  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] };
65
+ return value === undefined ? undefined : parseAnchorToken(value)!;
55
66
  }
56
67
 
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
- });
81
-
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
- });
68
+ /** Edit parameters; anchors must carry exactly `hashLen` hash characters. */
69
+ function buildEditSchema(hashLen: number) {
70
+ const pattern = anchorPattern(hashLen);
71
+ const requiredAnchor = Type.String({
72
+ pattern,
73
+ description: "LINE#HASH of the target line.",
74
+ });
75
+ const optionalEnd = Type.Optional(
76
+ Type.String({
77
+ pattern,
78
+ description: "Inclusive last LINE#HASH of the range; omit for one line.",
79
+ }),
80
+ );
81
+ const bodyLines = Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
82
+ description: "New lines, one per element, without CR/LF.",
83
+ });
84
+ const editOpSchema = Type.Union([
85
+ Type.Object(
86
+ {
87
+ op: Type.Literal("replace", { description: "Replace the cited line(s) with `body`." }),
88
+ anchor: requiredAnchor,
89
+ end: optionalEnd,
90
+ body: bodyLines,
91
+ },
92
+ { additionalProperties: false },
93
+ ),
94
+ Type.Object(
95
+ {
96
+ op: Type.Literal("delete", { description: "Delete the cited line(s)." }),
97
+ anchor: requiredAnchor,
98
+ end: optionalEnd,
99
+ },
100
+ { additionalProperties: false },
101
+ ),
102
+ Type.Object(
103
+ {
104
+ op: Type.Union([Type.Literal("insert_after"), Type.Literal("insert_before")], {
105
+ description:
106
+ "Insert body beside the anchor line, which is kept; do not repeat it in body.",
107
+ }),
108
+ anchor: requiredAnchor,
109
+ body: bodyLines,
110
+ },
111
+ { additionalProperties: false },
112
+ ),
113
+ Type.Object(
114
+ {
115
+ op: Type.Union([Type.Literal("append"), Type.Literal("prepend")], {
116
+ description: "Add body at the end or start of the file.",
117
+ }),
118
+ body: bodyLines,
119
+ },
120
+ { additionalProperties: false },
121
+ ),
122
+ ]);
123
+ return Type.Object(
124
+ {
125
+ path: Type.String({
126
+ minLength: 1,
127
+ description: "Path to the file (relative or absolute)",
128
+ }),
129
+ edits: Type.Array(editOpSchema, {
130
+ minItems: 1,
131
+ description: `Operations on one snapshot. Anchors are LINE#HASH with exactly ${hashLen} hash characters, copied from the latest read, grep, edit, or replace result.`,
132
+ }),
133
+ },
134
+ { additionalProperties: false },
135
+ );
88
136
  }
137
+ type EditSchema = ReturnType<typeof buildEditSchema>;
89
138
 
90
- const editSchema = createEditSchema(false);
91
- type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: ThenRunInput };
92
-
93
- type EditOpInput = Static<typeof editOpSchema>;
94
-
95
- /** Format failure mappings and complete unique-candidate rows within the detail budget. */
96
- function formatFailureDetails(
97
- failure: ApplyFailure,
98
- snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
99
- candidateLines: ReadonlySet<number>,
100
- ): string {
101
- if (failure.kind !== "anchor") return failure.message;
102
-
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.");
139
+ function createEditSchema(actionFusion: boolean, hashLen: number) {
140
+ return withThenRunSchema(
141
+ buildEditSchema(hashLen),
142
+ "Command to run after the edit succeeds; failure does not roll back the edit.",
143
+ actionFusion,
144
+ );
157
145
  }
146
+ type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
158
147
 
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
- }
148
+ type EditOpInput = Static<EditSchema>["edits"][number];
170
149
 
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}`;
150
+ /**
151
+ * Checks the schema cannot express, run before Pi's schema validation. Rejects body
152
+ * lines that cannot be written as UTF-8, anchor line numbers beyond the safe-integer
153
+ * range, and names anchors whose hash length differs from `hashLen` (the schema would
154
+ * report only a bare pattern mismatch). Malformed shapes are left to the schema.
155
+ * Arguments are never changed.
156
+ */
157
+ function checkEditArguments(args: unknown, hashLen: number): void {
158
+ const edits = (args as { edits?: unknown } | null)?.edits;
159
+ if (!Array.isArray(edits)) return;
160
+ const mismatches: string[] = [];
161
+ edits.forEach((op, index) => {
162
+ const body = (op as Record<string, unknown> | null)?.body;
163
+ if (Array.isArray(body)) {
164
+ body.forEach((line, lineIndex) => {
165
+ const reason = typeof line === "string" ? unwritableTextReason(line) : undefined;
166
+ if (reason) throw invalidArgument(`edits[${index}].body[${lineIndex}]`, reason);
167
+ });
168
+ }
169
+ for (const field of ["anchor", "end"] as const) {
170
+ const value = (op as Record<string, unknown> | null)?.[field];
171
+ if (typeof value !== "string") continue;
172
+ const token = parseAnchorToken(value);
173
+ if (token && !Number.isSafeInteger(token.line)) {
174
+ throw invalidArgument(
175
+ `edits[${index}].${field}`,
176
+ `line number in ${value} exceeds the safe integer range; copy a complete "LINE#HASH" token from the latest tool result.`,
177
+ );
178
+ }
179
+ if (token && token.hash.length !== hashLen) {
180
+ mismatches.push(
181
+ `edits[${index}].${field} ${value} has ${token.hash.length} hash characters`,
182
+ );
183
+ }
184
+ }
185
+ });
186
+ if (mismatches.length) {
187
+ throw new Error(
188
+ `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.`,
189
+ );
190
+ }
182
191
  }
183
192
 
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 };
193
+ /** Translate validated public operations into core edits, parsing numeric anchor positions. */
194
+ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
195
+ return ops.map((op) => {
196
+ switch (op.op) {
197
+ case "replace":
198
+ return {
199
+ op: "replace",
200
+ start: parseAnchor(op.anchor),
201
+ end: parseAnchor(op.end),
202
+ body: op.body,
203
+ };
204
+ case "delete":
205
+ return { op: "delete", start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
206
+ case "insert_after":
207
+ case "insert_before":
208
+ return { op: op.op, anchor: parseAnchor(op.anchor), body: op.body };
209
+ case "append":
210
+ case "prepend":
211
+ return { op: op.op, body: op.body };
212
+ }
213
+ });
217
214
  }
218
215
 
219
216
  /**
220
217
  * Return compact tokens for changed caller-supplied rows, retaining content for deletion successors.
221
218
  * Uses the applicator's final indices so mixed batches do not need a second position calculation.
222
219
  */
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));
220
+ function formatUpdatedAnchors(
221
+ before: string,
222
+ newText: string,
223
+ touched: readonly number[],
224
+ contextLines: readonly number[],
225
+ anchors: AnchorFormatter,
226
+ ): string {
227
+ const idxs = [...new Set(touched)].sort((a, b) => a - b);
228
+ return formatMutationAnchors(
229
+ splitLines(before),
230
+ splitLines(newText),
231
+ idxs,
232
+ anchors,
233
+ "Updated anchors:",
234
+ new Set(contextLines),
235
+ );
226
236
  }
227
237
 
228
238
  /** 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;
239
+ function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
240
+ let t = theme.fg("toolTitle", theme.bold("edit "));
241
+ t += theme.fg("accent", args.path);
242
+ const edits = Array.isArray(args.edits) ? args.edits : [];
243
+ const n = edits.length;
244
+ if (n) {
245
+ const kind = typeof edits[0]?.op === "string" ? edits[0].op : "unknown";
246
+ t += theme.fg("dim", ` — ${n} op${n > 1 ? "s" : ""}: ${kind}`);
247
+ }
248
+ if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
249
+ return t;
236
250
  }
237
251
 
238
- export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
239
- const parameters = createEditSchema(fusion !== undefined);
252
+ export function makeEditOverride(
253
+ cwd: string,
254
+ config: HashlineEditConfig,
255
+ fusion?: ActionFusionExecutor,
256
+ ) {
257
+ // Schema, verification, recovery, and returned anchors use the registered configuration.
258
+ const { hashLen, shiftRadius } = config;
259
+ const parameters = createEditSchema(fusion !== undefined, hashLen);
240
260
 
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,
261
+ return {
262
+ name: "edit" as const,
263
+ label: "edit",
264
+ description:
265
+ "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.",
266
+ promptSnippet: "Edit file lines using verified anchors",
267
+ promptGuidelines: [
268
+ "Batch related edits to one file in a single edit call; all its anchors are checked against one snapshot.",
269
+ "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.",
270
+ "On edit anchor failure, inspect the recovery candidates before retrying or re-reading.",
271
+ ...(fusion ? ACTION_FUSION_GUIDELINES : []),
272
+ ],
273
+ parameters,
274
+ prepareArguments(args: unknown): EditParams {
275
+ checkEditArguments(args, hashLen);
276
+ return args as EditParams;
277
+ },
278
+ renderShell: "default" as const,
254
279
 
255
- renderCall(args: EditParams, theme: any, context: any) {
256
- return renderMutationCall(args, theme, context, editHeader);
257
- },
280
+ renderCall(args: EditParams, theme: Theme, context: EditRenderContext) {
281
+ return renderMutationCall(args, theme, context, editHeader);
282
+ },
258
283
 
259
- renderResult(result: any, options: any, theme: any, context: any) {
260
- return renderMutationResult(result, options, theme, context, "Editing…", "Edited", editHeader);
261
- },
284
+ renderResult(
285
+ result: AgentToolResult<EditDetails>,
286
+ options: ToolRenderResultOptions,
287
+ theme: Theme,
288
+ context: EditRenderContext,
289
+ ) {
290
+ return renderMutationResult(
291
+ result,
292
+ options,
293
+ theme,
294
+ context,
295
+ "Editing…",
296
+ "Edited",
297
+ editHeader,
298
+ );
299
+ },
262
300
 
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
- };
301
+ async execute(
302
+ toolCallId: string,
303
+ params: EditParams,
304
+ signal: AbortSignal | undefined,
305
+ onUpdate: AgentToolUpdateCallback<EditDetails> | undefined,
306
+ ctx: ExtensionContext,
307
+ ) {
308
+ return executeMutation<Omit<EditParams, "then_run">, EditDetails>(
309
+ {
310
+ cwd,
311
+ fusion,
312
+ run: (mutationParams, target) =>
313
+ runHashline(target, mutationParams.edits, hashLen, shiftRadius),
314
+ },
315
+ { toolCallId, params, signal, onUpdate, ctx },
316
+ );
317
+ },
318
+ };
293
319
  }
294
320
 
295
- async function runHashline(
296
- absPath: string,
297
- displayPath: string,
298
- editOps: readonly EditOpInput[],
299
- signal: AbortSignal | undefined,
300
- onAnchors: (anchors: string) => void,
321
+ function runHashline(
322
+ target: MutationTarget,
323
+ editOps: readonly EditOpInput[],
324
+ hashLen: number,
325
+ shiftRadius: number,
301
326
  ) {
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);
327
+ const anchorFormatter = createAnchorFormatter(hashLen);
311
328
 
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
- }
329
+ return runTextMutation("edit", target, (currentText) => {
330
+ const translated = toCoreEdits(editOps);
319
331
 
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.`);
332
+ // Recovery reports checksum candidates from nearby lines, then the whole file
333
+ // if needed. Every failed anchor still rejects the batch; callers inspect
334
+ // candidates and resubmit with fresh anchors.
335
+ const result = applyEdits(currentText, translated, hashLen, shiftRadius);
336
+ if (!result.ok) {
337
+ throw new Error(
338
+ formatFailure(
339
+ result.failure,
340
+ { currentText, anchors: anchorFormatter },
341
+ translated.length > 1,
342
+ ),
343
+ );
344
+ }
322
345
 
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
- });
346
+ return {
347
+ text: result.text,
348
+ anchors: () =>
349
+ formatUpdatedAnchors(
350
+ currentText,
351
+ result.text,
352
+ result.touchedLines,
353
+ result.contextLines,
354
+ anchorFormatter,
355
+ ),
356
+ summary: () =>
357
+ `Edited ${target.displayPath} (${translated.length} op(s)${result.changed ? "" : ", no net change"}).`,
358
+ };
359
+ });
332
360
  }