@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +153 -2
  3. package/index.ts +282 -0
  4. package/package.json +79 -4
  5. package/prompts/find-guidelines.md +2 -0
  6. package/prompts/find-snippet.md +1 -0
  7. package/prompts/find.md +1 -0
  8. package/prompts/grep-guidelines.md +2 -0
  9. package/prompts/grep-snippet.md +1 -0
  10. package/prompts/grep.md +1 -0
  11. package/prompts/insert-guidelines.md +1 -0
  12. package/prompts/insert-snippet.md +1 -0
  13. package/prompts/insert.md +1 -0
  14. package/prompts/read-guidelines.md +2 -0
  15. package/prompts/read-snippet.md +1 -0
  16. package/prompts/read.md +1 -0
  17. package/prompts/replace-guidelines.md +4 -0
  18. package/prompts/replace-snippet.md +1 -0
  19. package/prompts/replace.md +1 -0
  20. package/prompts/undo-last-change-guidelines.md +1 -0
  21. package/prompts/undo-last-change-snippet.md +1 -0
  22. package/prompts/undo-last-change.md +1 -0
  23. package/src/anchor-registry.ts +977 -0
  24. package/src/auto-read-all-state.ts +27 -0
  25. package/src/auto-read-all.ts +477 -0
  26. package/src/batch.ts +767 -0
  27. package/src/commit.ts +137 -0
  28. package/src/config-ui.ts +212 -0
  29. package/src/config.ts +235 -0
  30. package/src/constants.ts +26 -0
  31. package/src/edit-common.ts +206 -0
  32. package/src/file-kind.ts +191 -0
  33. package/src/file-reader.ts +135 -0
  34. package/src/find.ts +244 -0
  35. package/src/fs-write.ts +231 -0
  36. package/src/glob.ts +186 -0
  37. package/src/grep.ts +690 -0
  38. package/src/hash-store/cache.ts +18 -0
  39. package/src/hash-store/retry.ts +44 -0
  40. package/src/hash-store/validation.ts +62 -0
  41. package/src/hash-store.ts +609 -0
  42. package/src/hashline/alphabet.ts +21 -0
  43. package/src/hashline/anchor-table.json +1 -0
  44. package/src/hashline/apply.ts +297 -0
  45. package/src/hashline/hash.ts +119 -0
  46. package/src/hashline/hasher.ts +47 -0
  47. package/src/hashline/index.ts +50 -0
  48. package/src/hashline/parse.ts +84 -0
  49. package/src/hashline/resolve.ts +373 -0
  50. package/src/insert.ts +258 -0
  51. package/src/normalize.ts +27 -0
  52. package/src/paths.ts +56 -0
  53. package/src/payload-contract.ts +133 -0
  54. package/src/prompts.ts +13 -0
  55. package/src/read.ts +286 -0
  56. package/src/replace-diff.ts +610 -0
  57. package/src/replace-render.ts +390 -0
  58. package/src/replace-response.ts +166 -0
  59. package/src/replace-undo.ts +270 -0
  60. package/src/replace.ts +318 -0
  61. package/src/served.ts +36 -0
  62. package/src/utils.ts +387 -0
  63. package/src/validation.ts +45 -0
  64. package/src/write-hook.ts +53 -0
@@ -0,0 +1,390 @@
1
+ import { Markdown, Text } from "@earendil-works/pi-tui";
2
+ import { keyHint, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import type { ReplaceDetails } from "./replace";
4
+ import { abortedBatchMessageFor } from "./batch";
5
+ import { withLineNumbers } from "./utils";
6
+ import { getPreviewInput } from "./payload-contract";
7
+ export { getPreviewInput };
8
+
9
+ export type FgT = Pick<Theme, "fg">;
10
+ export type CallT = Pick<Theme, "fg" | "bold">;
11
+ export type MdTheme = Pick<
12
+ Theme,
13
+ "fg" | "bold" | "italic" | "underline" | "strikethrough"
14
+ >;
15
+
16
+ export type RPreview = { diff: string; path?: string } | { error: string; path?: string };
17
+ export type RRState = {
18
+ argsKey?: string;
19
+ preview?: RPreview;
20
+ previewGeneration?: number;
21
+ previewTimer?: ReturnType<typeof setTimeout>;
22
+ previewAbort?: AbortController;
23
+ resolvedPath?: string;
24
+ };
25
+
26
+ type DiffRowKind = "added" | "removed" | "context";
27
+
28
+ function diffRowKind(line: string): DiffRowKind {
29
+ const withoutGutter = line.replace(/^\s*\d+\s+│\s*/, "");
30
+ if (withoutGutter.startsWith("+") && !withoutGutter.startsWith("+++")) return "added";
31
+ if (withoutGutter.startsWith("-") && !withoutGutter.startsWith("---")) return "removed";
32
+ return "context";
33
+ }
34
+
35
+ export function colorLines(lines: string[], theme: FgT): string[] {
36
+ return lines.map((line) => {
37
+ const kind = diffRowKind(line);
38
+ if (kind === "added") return theme.fg("success", line);
39
+ if (kind === "removed") return theme.fg("error", line);
40
+ return theme.fg("dim", line);
41
+ });
42
+ }
43
+ export function toNumberedDiff(diff: string, lineNumbers: (number | null | undefined)[]): string {
44
+ return withLineNumbers(diff, lineNumbers);
45
+ }
46
+
47
+ export function fmtPreview(
48
+ diff: string,
49
+ expanded: boolean,
50
+ theme: FgT,
51
+ ): string {
52
+ const lines = diff.split("\n");
53
+ const maxLines = expanded ? 40 : 16;
54
+ const shown = colorLines(lines.slice(0, maxLines), theme);
55
+
56
+ if (lines.length > maxLines) {
57
+ shown.push(
58
+ theme.fg("muted", `... ${lines.length - maxLines} more diff lines`),
59
+ );
60
+ }
61
+ return shown.join("\n");
62
+ }
63
+
64
+ export function fmtResult(diff: string, theme: FgT): string {
65
+ return colorLines(diff.split("\n"), theme).join("\n");
66
+ }
67
+
68
+ export function highlightBatchRefs(text: string, theme: FgT): string {
69
+ const pattern = /\b([Bb]atch \d+)\b/g;
70
+ const sections: string[] = [];
71
+ let cursor = 0;
72
+ for (;;) {
73
+ const match = pattern.exec(text);
74
+ if (!match) break;
75
+ if (match.index > cursor) sections.push(theme.fg("error", text.slice(cursor, match.index)));
76
+ sections.push(theme.fg("warning", match[0]));
77
+ cursor = match.index + match[0].length;
78
+ }
79
+ if (cursor < text.length) sections.push(theme.fg("error", text.slice(cursor)));
80
+ return sections.join("");
81
+ }
82
+
83
+ export function fmtCall(
84
+ args: { path?: string; remove_from?: string; remove_to?: string; anchor?: string } | undefined,
85
+ state: RRState,
86
+ expanded: boolean,
87
+ theme: CallT,
88
+ toolName = "replace",
89
+ ): string {
90
+ const previewPath = state.preview && "path" in state.preview ? state.preview.path : undefined;
91
+ const path = args?.path ?? state.resolvedPath ?? previewPath;
92
+ const anchorFallback = typeof args?.remove_from === "string" && typeof args?.remove_to === "string" ? `${args.remove_from}→${args.remove_to}` : typeof args?.anchor === "string" ? args.anchor : undefined;
93
+ const pathDisplay =
94
+ typeof path === "string" && path.length > 0
95
+ ? theme.fg("accent", path)
96
+ : typeof anchorFallback === "string" && anchorFallback.length > 0
97
+ ? theme.fg("accent", anchorFallback)
98
+ : theme.fg("toolOutput", "...");
99
+ let text = `${theme.fg("toolTitle", theme.bold(toolName))} ${pathDisplay}`;
100
+
101
+ if (!state.preview) {
102
+ return text;
103
+ }
104
+
105
+ if ("error" in state.preview) {
106
+ text += `\n\n${theme.fg("error", state.preview.error)}`;
107
+ return text;
108
+ }
109
+
110
+ if (state.preview.diff) {
111
+ text += `\n\n${fmtPreview(state.preview.diff, expanded, theme)}`;
112
+ }
113
+ return text;
114
+ }
115
+
116
+ export function getResultText(result: {
117
+ content?: Array<{ type: string; text?: string }>;
118
+ }): string | undefined {
119
+ const textContent = result.content?.find(
120
+ (entry): entry is { type: "text"; text: string } =>
121
+ entry.type === "text" && typeof entry.text === "string",
122
+ );
123
+ return textContent?.text;
124
+ }
125
+
126
+ export function extractWarnings(
127
+ text: string | undefined,
128
+ ): string | undefined {
129
+ return text?.match(/(?:^|\n)Warnings:\n[\s\S]*$/)?.[0]?.trimStart();
130
+ }
131
+
132
+ export function isApplied(
133
+ details: ReplaceDetails | undefined,
134
+ ): boolean {
135
+ const metrics = details?.metrics;
136
+ return (
137
+ metrics?.classification === "applied" &&
138
+ metrics.added_lines !== undefined &&
139
+ metrics.removed_lines !== undefined
140
+ );
141
+ }
142
+
143
+ const RESULT_PREVIEW_LINES = 16;
144
+
145
+ export function expandHint(): string {
146
+ try {
147
+ return keyHint("app.tools.expand", "to expand");
148
+ } catch {
149
+ return "ctrl+o to expand";
150
+ }
151
+ }
152
+
153
+ function extractSummary(text: string | undefined): string | undefined {
154
+ if (!text) return undefined;
155
+ if (text.includes("│")) return undefined;
156
+ const warningsIdx = text.indexOf("\n\nWarnings:");
157
+ const summary = warningsIdx >= 0 ? text.slice(0, warningsIdx) : text;
158
+ return summary.length > 0 ? summary : undefined;
159
+ }
160
+
161
+ const BATCH_HEADER_RE = /^batch \d+:\n/;
162
+
163
+ function splitBatchHeader(diff: string, lineNumbers: (number | null | undefined)[] | undefined): { header: string | undefined; body: string; lineNumbers: (number | null | undefined)[] | undefined } {
164
+ const match = diff.match(BATCH_HEADER_RE);
165
+ if (!match) return { header: undefined, body: diff, lineNumbers };
166
+ return { header: match[0]!.slice(0, -1), body: diff.slice(match[0].length), lineNumbers: lineNumbers?.slice(1) };
167
+ }
168
+
169
+ export function buildAppliedText(
170
+ text: string | undefined,
171
+ details: ReplaceDetails | undefined,
172
+ theme: FgT,
173
+ expanded: boolean,
174
+ ): string | undefined {
175
+ const sections: string[] = [];
176
+ const summary = extractSummary(text);
177
+ if (summary) sections.push(summary);
178
+ if (details?.diff) {
179
+ const { header, body, lineNumbers } = splitBatchHeader(details.diff, details.diffLineNumbers);
180
+ const rawDiff = lineNumbers ? toNumberedDiff(body, lineNumbers) : body;
181
+ const diffLines = body.split("\n");
182
+ const diffSection = expanded
183
+ ? fmtResult(rawDiff, theme)
184
+ : fmtPreview(rawDiff, false, theme);
185
+ const hint =
186
+ !expanded && diffLines.length > RESULT_PREVIEW_LINES
187
+ ? ` (${expandHint()})`
188
+ : "";
189
+ sections.push(header !== undefined ? `${theme.fg("warning", header)}\n${diffSection}${hint}` : `${diffSection}${hint}`);
190
+ }
191
+ const warnings = details?.warnings?.length ? `Warnings:\n${details.warnings.join("\n")}` : extractWarnings(text);
192
+ if (warnings) sections.push(warnings);
193
+ return sections.length > 0 ? sections.join("\n\n") : undefined;
194
+ }
195
+
196
+ function trimEmpty(lines: string[]): string[] {
197
+ let start = 0;
198
+ let end = lines.length;
199
+
200
+ while (start < end && lines[start] === "") {
201
+ start++;
202
+ }
203
+ while (end > start && lines[end - 1] === "") {
204
+ end--;
205
+ }
206
+
207
+ return lines.slice(start, end);
208
+ }
209
+
210
+ export function fmtResultMd(text: string): string {
211
+ return trimEmpty(text.split("\n")).join("\n");
212
+ }
213
+
214
+ export function mkMdTheme(theme: MdTheme) {
215
+ return {
216
+ heading: (text: string) => theme.fg("mdHeading", text),
217
+ link: (text: string) => theme.fg("mdLink", text),
218
+ linkUrl: (text: string) => theme.fg("mdLinkUrl", text),
219
+ code: (text: string) => theme.fg("mdCode", text),
220
+ codeBlock: (text: string) => theme.fg("mdCodeBlock", text),
221
+ codeBlockBorder: (text: string) => theme.fg("mdCodeBlockBorder", text),
222
+ quote: (text: string) => theme.fg("mdQuote", text),
223
+ quoteBorder: (text: string) => theme.fg("mdQuoteBorder", text),
224
+ hr: (text: string) => theme.fg("mdHr", text),
225
+ listBullet: (text: string) => theme.fg("mdListBullet", text),
226
+ bold: (text: string) => theme.bold(text),
227
+ italic: (text: string) => (theme.italic ? theme.italic(text) : text),
228
+ underline: (text: string) =>
229
+ theme.underline ? theme.underline(text) : text,
230
+ strikethrough: (text: string) =>
231
+ theme.strikethrough ? theme.strikethrough(text) : text,
232
+ highlightCode: (code: string, lang?: string) =>
233
+ code.split("\n").map((line) => {
234
+ if (lang === "diff") {
235
+ const kind = diffRowKind(line);
236
+ if (kind === "added") return theme.fg("toolDiffAdded", line);
237
+ if (kind === "removed") return theme.fg("toolDiffRemoved", line);
238
+ return theme.fg("toolDiffContext", line);
239
+ }
240
+
241
+ return theme.fg("mdCodeBlock", line);
242
+ }),
243
+ };
244
+ }
245
+
246
+ export const PREVIEW_DEBOUNCE_MS = 150;
247
+
248
+ export function reuseText(context: any, content: string): Text {
249
+ const t = context.lastComponent instanceof Text
250
+ ? context.lastComponent
251
+ : new Text("", 0, 0);
252
+ t.setText(content);
253
+ return t;
254
+ }
255
+
256
+ export function reuseMarkdown(context: any, content: string, theme: any): Markdown {
257
+ const m = context.lastComponent instanceof Markdown
258
+ ? context.lastComponent
259
+ : new Markdown("", 0, 0, mkMdTheme(theme));
260
+ m.setText(content);
261
+ return m;
262
+ }
263
+
264
+ export function makeRenderCall(
265
+ preview: (args: unknown, cwd: string, signal?: AbortSignal) => Promise<RPreview>,
266
+ options: {
267
+ getInput?: (args: unknown) => { path?: string; remove_from?: string; remove_to?: string; anchor?: string } | null;
268
+ toolName?: string;
269
+ resolveTarget?: (input: { remove_from?: string; remove_to?: string; anchor?: string }) => string | undefined;
270
+ } = {},
271
+ ) {
272
+ const getInput = options.getInput ?? getPreviewInput;
273
+ const toolName = options.toolName ?? "replace";
274
+ return (args: any, theme: CallT, context: any): Text => {
275
+ const previewInput = getInput(args);
276
+ if (!context.executionStarted && previewInput) {
277
+ const resolved = options.resolveTarget?.(previewInput);
278
+ context.state.resolvedPath = resolved;
279
+ }
280
+ const cancelPendingPreview = () => {
281
+ if (context.state.previewTimer) {
282
+ clearTimeout(context.state.previewTimer);
283
+ context.state.previewTimer = undefined;
284
+ }
285
+ if (context.state.previewAbort) {
286
+ context.state.previewAbort.abort();
287
+ context.state.previewAbort = undefined;
288
+ }
289
+ };
290
+ if (context.executionStarted) {
291
+ cancelPendingPreview();
292
+ context.state.argsKey = undefined;
293
+ context.state.preview = undefined;
294
+ context.state.previewGeneration = (context.state.previewGeneration ?? 0) + 1;
295
+ } else if (!context.argsComplete || !previewInput) {
296
+ cancelPendingPreview();
297
+ context.state.argsKey = undefined;
298
+ context.state.preview = undefined;
299
+ context.state.previewGeneration = (context.state.previewGeneration ?? 0) + 1;
300
+ } else {
301
+ const argsKey = JSON.stringify(previewInput);
302
+ if (context.state.argsKey !== argsKey) {
303
+ cancelPendingPreview();
304
+ context.state.argsKey = argsKey;
305
+ context.state.preview = undefined;
306
+ const previewGeneration = (context.state.previewGeneration ?? 0) + 1;
307
+ context.state.previewGeneration = previewGeneration;
308
+ context.state.previewTimer = setTimeout(() => {
309
+ context.state.previewTimer = undefined;
310
+ const controller = new AbortController();
311
+ context.state.previewAbort = controller;
312
+ preview(args, context.cwd, controller.signal)
313
+ .then((result) => {
314
+ if (controller.signal.aborted) return;
315
+ if (context.state.previewAbort === controller) context.state.previewAbort = undefined;
316
+ if (
317
+ context.state.argsKey === argsKey &&
318
+ context.state.previewGeneration === previewGeneration
319
+ ) {
320
+ context.state.preview = result;
321
+ context.invalidate();
322
+ }
323
+ })
324
+ .catch((err: unknown) => {
325
+ if (controller.signal.aborted) return;
326
+ if (context.state.previewAbort === controller) context.state.previewAbort = undefined;
327
+ if (
328
+ context.state.argsKey === argsKey &&
329
+ context.state.previewGeneration === previewGeneration
330
+ ) {
331
+ context.state.preview = {
332
+ error: err instanceof Error ? err.message : String(err),
333
+ };
334
+ context.invalidate();
335
+ }
336
+ });
337
+ }, PREVIEW_DEBOUNCE_MS);
338
+ }
339
+ }
340
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
341
+ text.setText(fmtCall(getInput(args) ?? undefined, context.state as RRState, context.expanded, theme, toolName));
342
+ return text;
343
+ };
344
+ }
345
+
346
+ export function renderEditResult(
347
+ result: { content?: Array<{ type: string; text?: string }>; details?: ReplaceDetails },
348
+ options: { isPartial: boolean; expanded?: boolean } | boolean,
349
+ theme: FgT,
350
+ context: any,
351
+ ): Text | Markdown {
352
+ const isPartial = typeof options === "boolean" ? options : options.isPartial;
353
+ const optionsExpanded = typeof options === "boolean" ? undefined : options.expanded;
354
+ if (isPartial) return reuseText(context, theme.fg("warning", "Editing..."));
355
+ const renderedText = getResultText(result);
356
+ const renderState = context.state as RRState | undefined;
357
+ if (renderState) {
358
+ if (renderState.previewTimer) {
359
+ clearTimeout(renderState.previewTimer);
360
+ renderState.previewTimer = undefined;
361
+ }
362
+ if (renderState.previewAbort) {
363
+ renderState.previewAbort.abort();
364
+ renderState.previewAbort = undefined;
365
+ }
366
+ renderState.preview = undefined;
367
+ renderState.previewGeneration = (renderState.previewGeneration ?? 0) + 1;
368
+ }
369
+ const batch = result.details?.batch;
370
+ if (batch && batch.last === false) {
371
+ const abortedMessage = typeof context?.toolCallId === "string" ? abortedBatchMessageFor(context.toolCallId) : undefined;
372
+ if (abortedMessage !== undefined) {
373
+ return reuseText(context, `\n${highlightBatchRefs(abortedMessage, theme)}`);
374
+ }
375
+ return reuseText(context, theme.fg("warning", `In batch ${batch.id}`));
376
+ }
377
+ if (context.isError) {
378
+ return renderedText
379
+ ? reuseText(context, `\n${highlightBatchRefs(renderedText, theme)}`)
380
+ : new Text("", 0, 0);
381
+ }
382
+ if (isApplied(result.details)) {
383
+ const isExpanded = optionsExpanded === true || context.expanded === true;
384
+ const appliedText = buildAppliedText(renderedText, result.details, theme, isExpanded);
385
+ return appliedText ? reuseText(context, appliedText) : new Text("", 0, 0);
386
+ }
387
+ if (!renderedText) return new Text("", 0, 0);
388
+ return reuseMarkdown(context, fmtResultMd(renderedText), theme);
389
+ }
390
+
@@ -0,0 +1,166 @@
1
+ import type { NEdit } from "./hashline";
2
+ import type { ReplaceDetails } from "./replace";
3
+ import { genDiff, genPatch, type DiffSpan } from "./replace-diff";
4
+ import { visLines, clipLine } from "./utils";
5
+
6
+ export type TResult = {
7
+ content: Array<{ type: "text"; text: string }>;
8
+ isError?: boolean;
9
+ details: ReplaceDetails;
10
+ };
11
+
12
+ export type RMetrics = {
13
+ edits_attempted: number;
14
+ edits_noop: number;
15
+ warnings: number;
16
+ classification: "applied" | "noop";
17
+ changed_lines?: { first: number; last: number };
18
+ added_lines?: number;
19
+ removed_lines?: number;
20
+ };
21
+
22
+ export type RMeta = {
23
+ editsAttempted: number;
24
+ noopEditsCount: number;
25
+ firstChangedLine?: number;
26
+ lastChangedLine?: number;
27
+ addedLines: number;
28
+ removedLines: number;
29
+ };
30
+
31
+ export interface NoopInput {
32
+ path: string;
33
+ noopEdit: NEdit | undefined;
34
+ snapshotId?: string;
35
+ editMeta: RMeta;
36
+ warnings: string[] | undefined;
37
+ }
38
+
39
+ export interface SuccessInput {
40
+ path: string;
41
+ originalNormalized: string;
42
+ originalHashes: string[];
43
+ result: string;
44
+ resultHashes: string[];
45
+ warnings: string[] | undefined;
46
+ snapshotId?: string;
47
+ editMeta: RMeta;
48
+ spans?: DiffSpan[];
49
+ }
50
+
51
+
52
+ export function buildMetrics(args: {
53
+ classification: "applied" | "noop";
54
+ editsAttempted: number;
55
+ noopEditsCount: number;
56
+ warningsCount: number;
57
+ firstChangedLine?: number;
58
+ lastChangedLine?: number;
59
+ addedLines?: number;
60
+ removedLines?: number;
61
+ }): RMetrics {
62
+ const metrics: RMetrics = {
63
+ edits_attempted: args.editsAttempted,
64
+ edits_noop: args.noopEditsCount,
65
+ warnings: args.warningsCount,
66
+ classification: args.classification,
67
+ };
68
+ if (
69
+ args.classification === "applied" &&
70
+ args.firstChangedLine !== undefined &&
71
+ args.lastChangedLine !== undefined
72
+ ) {
73
+ metrics.changed_lines = {
74
+ first: args.firstChangedLine,
75
+ last: args.lastChangedLine,
76
+ };
77
+ }
78
+ if (args.addedLines !== undefined) metrics.added_lines = args.addedLines;
79
+ if (args.removedLines !== undefined)
80
+ metrics.removed_lines = args.removedLines;
81
+ return metrics;
82
+ }
83
+
84
+ function warnBlock(warnings: string[] | undefined): string {
85
+ return warnings?.length ? `\n\nWarnings:\n${warnings.join("\n")}` : "";
86
+ }
87
+
88
+ export function buildNoop(input: NoopInput, noopNoun = "Replacement"): TResult {
89
+ const {
90
+ path,
91
+ noopEdit,
92
+ snapshotId,
93
+ editMeta,
94
+ warnings,
95
+ } = input;
96
+
97
+ const noopDetailsText = noopEdit
98
+ ? `${noopNoun} for ${noopEdit.loc} is identical to current content:\n ${noopEdit.loc}: ${clipLine(noopEdit.currentContent)}`
99
+ : "The edit produced identical content.";
100
+ const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(warnings)}`;
101
+
102
+ const metrics = buildMetrics({
103
+ classification: "noop",
104
+ editsAttempted: editMeta.editsAttempted,
105
+ noopEditsCount: editMeta.noopEditsCount,
106
+ warningsCount: warnings?.length ?? 0,
107
+ });
108
+
109
+ return {
110
+ content: [{ type: "text", text }],
111
+ details: {
112
+ diff: "",
113
+ patch: "",
114
+ firstChangedLine: undefined,
115
+ snapshotId,
116
+ classification: "noop" as const,
117
+ metrics,
118
+ ...(warnings?.length ? { warnings: [...warnings] } : {}),
119
+ },
120
+ };
121
+ }
122
+
123
+ export function buildChanged(input: SuccessInput, verb = "replaced", diffContextLines = 1): TResult {
124
+ const { path, result, warnings, snapshotId, originalNormalized, originalHashes, editMeta, resultHashes, spans } = input;
125
+ const resultLines = visLines(result);
126
+ const diffResult = genDiff(originalNormalized, result, diffContextLines, resultHashes, originalHashes, undefined, spans);
127
+ const addedLines = editMeta.addedLines;
128
+ const removedLines = editMeta.removedLines;
129
+ const warningsBlock = warnBlock(warnings);
130
+ const successPrefix = `Successfully ${verb} in ${path}.`;
131
+ const lineSummary = addedLines > 0 || removedLines > 0
132
+ ? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
133
+ : "";
134
+ const text = resultLines.length === 0
135
+ ? "File is empty. Use replace to insert content."
136
+ : warningsBlock
137
+ ? `${successPrefix}${lineSummary}${warningsBlock}`
138
+ : `${successPrefix}${lineSummary}`;
139
+
140
+ const metrics = buildMetrics({
141
+ classification: "applied",
142
+ editsAttempted: editMeta.editsAttempted,
143
+ noopEditsCount: editMeta.noopEditsCount,
144
+ warningsCount: warnings?.length ?? 0,
145
+ firstChangedLine: editMeta.firstChangedLine,
146
+ lastChangedLine: editMeta.lastChangedLine,
147
+ addedLines,
148
+ removedLines,
149
+ });
150
+
151
+ const patchResult = genPatch(path, originalNormalized, result);
152
+ return {
153
+ content: [{ type: "text", text }],
154
+ details: {
155
+ diff: diffResult.diff,
156
+ patch: patchResult.patch,
157
+ ...(patchResult.truncated ? { patchTruncated: true as const } : {}),
158
+ firstChangedLine:
159
+ editMeta.firstChangedLine ?? diffResult.firstChangedLine,
160
+ snapshotId,
161
+ metrics,
162
+ diffLineNumbers: diffResult.lineNumbers.map((line) => line ?? null),
163
+ ...(warnings?.length ? { warnings: [...warnings] } : {}),
164
+ },
165
+ };
166
+ }