@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,373 @@
1
+ import { abortIf, rejectUnknownFields, clipLine, decodeStringArray, assertNoNul } from "../utils";
2
+ import { parseHashRef, parseText, type Anchor } from "./parse";
3
+ import { HASH_SEP, stripRowPrefix, lineChecksum, type RowPrefixKind } from "./hash";
4
+ import { HASH_RUN } from "./alphabet";
5
+ import { NEW_CONTENT_NOT_ARRAY_MSG, MAX_RANGE_STALE_LINES } from "../constants";
6
+
7
+ export type RAnchor = {
8
+ line: number;
9
+ hash: string;
10
+ };
11
+
12
+ export type HEdit = { content_lines: string[]; hash_bounds: [Anchor, Anchor] };
13
+ export type RHEdit = {
14
+ content_lines: string[];
15
+ hash_bounds: [RAnchor, RAnchor];
16
+ };
17
+
18
+ interface HMismatch {
19
+ ref: Anchor;
20
+ kind: "not_found";
21
+ context?: RAnchor;
22
+ }
23
+
24
+ export interface NEdit {
25
+ loc: string;
26
+ currentContent: string;
27
+ }
28
+
29
+ export type HTEdit = {
30
+ replacement_lines: string[];
31
+ remove_from: string;
32
+ remove_to: string;
33
+ };
34
+
35
+ function resAnchorFromMap(
36
+ ref: Anchor,
37
+ hashIndex: Map<string, number[]>,
38
+ ): RAnchor | HMismatch {
39
+ const hashMatches = hashIndex.get(ref.hash);
40
+ if (!hashMatches || hashMatches.length === 0) {
41
+ return { ref, kind: "not_found" };
42
+ }
43
+ return {
44
+ line: hashMatches[0]!,
45
+ hash: ref.hash,
46
+ };
47
+ }
48
+
49
+ function assertAligned(
50
+ fileLines: string[],
51
+ fileHashes: string[],
52
+ ctx: string,
53
+ ): void {
54
+ if (fileHashes.length !== fileLines.length) {
55
+ throw new Error(
56
+ `${ctx}: fileHashes.length (${fileHashes.length}) must match fileLines.length (${fileLines.length}).`,
57
+ );
58
+ }
59
+ }
60
+
61
+ export function fmtRow(hash: string, line: string): string {
62
+ return `${hash}${HASH_SEP}${line}`;
63
+ }
64
+
65
+ export function fmtRegion(hashes: string[], lines: string[]): string {
66
+ if (hashes.length !== lines.length) {
67
+ throw new Error(
68
+ `fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`,
69
+ );
70
+ }
71
+ return lines.map((line, index) => fmtRow(hashes[index]!, line)).join("\n");
72
+ }
73
+
74
+ export function fmtMismatchWithHashes(
75
+ mismatches: HMismatch[],
76
+ fileLines: string[],
77
+ fileHashes: string[],
78
+ filePath?: string,
79
+ ): { text: string; hashes: string[]; servedMap: Map<string, string> } {
80
+ assertAligned(fileLines, fileHashes, "fmtMismatch");
81
+ const out: string[] = [];
82
+ const hashes: string[] = [];
83
+ const servedMap = new Map<string, string>();
84
+ const notFound = mismatches;
85
+ if (notFound.length > 0) {
86
+ const refList = notFound.map((m) => `"${m.ref.hash}"`).join(", ");
87
+ out.push(
88
+ `[E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. The file changed since read. Call read()${filePath ? ` on ${filePath}` : ""} for fresh anchors.`
89
+ );
90
+ for (const m of notFound) {
91
+ const ctx = m.context;
92
+ if (!ctx) continue;
93
+ const from = Math.max(1, ctx.line - 1);
94
+ const to = Math.min(fileLines.length, ctx.line + 1);
95
+ const rows: string[] = [];
96
+ for (let ln = from; ln <= to; ln++) {
97
+ const h = fileHashes[ln - 1]!;
98
+ const c = fileLines[ln - 1] ?? "";
99
+ hashes.push(h);
100
+ servedMap.set(h, lineChecksum(c));
101
+ rows.push(` ${ln}: ${h}│${clipLine(c)}`);
102
+ }
103
+ out.push("");
104
+ out.push(` Current context around resolved anchor "${ctx.hash}" (line ${ctx.line}):\n${rows.join("\n")}`);
105
+ }
106
+ }
107
+ return { text: out.join("\n"), hashes, servedMap };
108
+ }
109
+
110
+
111
+ const ITEM_KS = new Set(["replacement_lines", "remove_from", "remove_to"]);
112
+
113
+ function assertItem(edit: Record<string, unknown>): void {
114
+ rejectUnknownFields(edit, ITEM_KS, "Edit", "The edit takes only { replacement_lines, remove_from, remove_to }.");
115
+
116
+ if ("remove_from" in edit && typeof edit.remove_from !== "string") {
117
+ throw new Error(
118
+ `[E_BAD_SHAPE] Field "remove_from" must be an anchor string (4-char anchor).`,
119
+ );
120
+ }
121
+ if ("remove_to" in edit && typeof edit.remove_to !== "string") {
122
+ throw new Error(
123
+ `[E_BAD_SHAPE] Field "remove_to" must be an anchor string (4-char anchor).`,
124
+ );
125
+ }
126
+ if (!("replacement_lines" in edit)) {
127
+ throw new Error(`[E_BAD_SHAPE] The edit requires a "replacement_lines" array (use [] to delete).`);
128
+ }
129
+ if (!Array.isArray(edit.replacement_lines) || edit.replacement_lines.some((line) => typeof line !== "string")) {
130
+ throw new Error(NEW_CONTENT_NOT_ARRAY_MSG);
131
+ }
132
+ if (typeof edit.remove_from !== "string" || typeof edit.remove_to !== "string") {
133
+ throw new Error(
134
+ `[E_BAD_SHAPE] The edit requires "remove_from" and "remove_to" anchor strings (4-char anchors from read output).`,
135
+ );
136
+ }
137
+ }
138
+
139
+ export const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_RUN})│`);
140
+
141
+ export function stripAnchorRow(
142
+ trimmed: string,
143
+ entryLabel: string,
144
+ warnings?: string[],
145
+ ): string {
146
+ const match = trimmed.match(ANCHOR_ROW_RE);
147
+ if (!match) return trimmed;
148
+ const marker =
149
+ match[1] === "+"
150
+ ? "diff-preview marker"
151
+ : match[1] === "-"
152
+ ? 'leading "-" marker'
153
+ : '"anchor│" prefix';
154
+ warnings?.push(`[W_BAD_REF] Stripped ${marker} from ${entryLabel} "${clipLine(trimmed, 48)}".`);
155
+ return match[2]!;
156
+ }
157
+
158
+ export function resEdit(edit: HTEdit, warnings?: string[]): HEdit {
159
+ assertItem(edit as Record<string, unknown>);
160
+
161
+ const replaceLines = parseText(decodeStringArray(edit.replacement_lines, warnings) ?? edit.replacement_lines);
162
+ assertNoNul(replaceLines);
163
+ const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
164
+ return stripAnchorRow(ref.trim(), "remove_from/remove_to entry", warnings);
165
+ }) as [string, string];
166
+ return {
167
+ content_lines: replaceLines,
168
+ hash_bounds: [parseHashRef(bounds[0]), parseHashRef(bounds[1])],
169
+ };
170
+ }
171
+
172
+ function warnUnicodeEsc(
173
+ edit: HEdit,
174
+ warnings: string[],
175
+ ): void {
176
+ if (edit.content_lines.some((line) => /\\uDDDD/i.test(line))) {
177
+ warnings.push(
178
+ "Detected literal \\uDDDD in edit content; no autocorrection applied.",
179
+ );
180
+ }
181
+ }
182
+
183
+ function stripRowPrefixes(
184
+ edit: HEdit,
185
+ warnings: string[],
186
+ kinds: RowPrefixKind[],
187
+ code: string,
188
+ marker: string,
189
+ ): HEdit {
190
+ const stripped: number[] = [];
191
+ const contentLines = edit.content_lines.map((line, lineIndex) => {
192
+ const result = stripRowPrefix(line);
193
+ if (result.kind === null || !kinds.includes(result.kind)) return line;
194
+ stripped.push(lineIndex);
195
+ return result.text;
196
+ });
197
+ if (stripped.length === 0) return edit;
198
+ const locations = stripped.map((i) => `replacement_lines line ${i + 1}`).join(", ");
199
+ warnings.push(`${code} Stripped ${marker} from ${locations}.`);
200
+ return { ...edit, content_lines: contentLines };
201
+ }
202
+
203
+ export function stripBarePrefixes(edit: HEdit, warnings: string[]): HEdit {
204
+ return stripRowPrefixes(edit, warnings, ["bare"], "[W_BARE_HASH_PREFIX]", '"anchor│" prefix');
205
+ }
206
+
207
+ export function stripDiffPrefixes(edit: HEdit, warnings: string[]): HEdit {
208
+ return stripRowPrefixes(edit, warnings, ["plus", "minus"], "[W_INVALID_PATCH]", "diff-preview marker");
209
+ }
210
+
211
+ export function swapReversedRanges(
212
+ edit: HEdit,
213
+ fileHashes: string[],
214
+ ): HEdit {
215
+ const lineByHash = new Map<string, number>();
216
+ for (let i = 0; i < fileHashes.length; i++) {
217
+ lineByHash.set(fileHashes[i]!, i + 1);
218
+ }
219
+ const [startRef, endRef] = edit.hash_bounds;
220
+ const startLine = lineByHash.get(startRef.hash);
221
+ const endLine = lineByHash.get(endRef.hash);
222
+ if (
223
+ startLine === undefined ||
224
+ endLine === undefined ||
225
+ startLine <= endLine
226
+ ) {
227
+ return edit;
228
+ }
229
+ return { ...edit, hash_bounds: [endRef, startRef] as [Anchor, Anchor] };
230
+ }
231
+
232
+ export function valEdit(
233
+ edit: HEdit,
234
+ fileLines: string[],
235
+ fileHashes: string[],
236
+ warnings: string[],
237
+ signal: AbortSignal | undefined,
238
+ ): { resolved: RHEdit | undefined; mismatches: HMismatch[] } {
239
+ assertAligned(fileLines, fileHashes, "valEdit");
240
+ const mismatches: HMismatch[] = [];
241
+
242
+ const hashIndex = new Map<string, number[]>();
243
+ for (let i = 0; i < fileHashes.length; i++) {
244
+ const h = fileHashes[i]!;
245
+ const list = hashIndex.get(h) ?? [];
246
+ list.push(i + 1);
247
+ hashIndex.set(h, list);
248
+ }
249
+
250
+ const tryResolve = (ref: Anchor): RAnchor | undefined => {
251
+ const result = resAnchorFromMap(ref, hashIndex);
252
+ if ("kind" in result) {
253
+ mismatches.push(result);
254
+ return undefined;
255
+ }
256
+ return result;
257
+ };
258
+
259
+ abortIf(signal);
260
+ const startResolved = tryResolve(edit.hash_bounds[0]);
261
+ const endResolved = tryResolve(edit.hash_bounds[1]);
262
+ if (!startResolved || !endResolved) {
263
+ if (!startResolved && endResolved) {
264
+ const startMismatch = mismatches.findLast((m) => m.ref === edit.hash_bounds[0]);
265
+ if (startMismatch && startMismatch.kind === "not_found") startMismatch.context = endResolved;
266
+ } else if (startResolved && !endResolved) {
267
+ const endMismatch = mismatches.findLast((m) => m.ref === edit.hash_bounds[1]);
268
+ if (endMismatch && endMismatch.kind === "not_found") endMismatch.context = startResolved;
269
+ }
270
+ return { resolved: undefined, mismatches };
271
+ }
272
+ return {
273
+ resolved: {
274
+ content_lines: edit.content_lines,
275
+ hash_bounds: [startResolved, endResolved],
276
+ },
277
+ mismatches,
278
+ };
279
+ }
280
+
281
+ export function resolveAnchorLine(
282
+ ref: Anchor,
283
+ fileLines: string[],
284
+ fileHashes: string[],
285
+ filePath?: string,
286
+ ): number {
287
+ const { resolved, mismatches } = valEdit(
288
+ { hash_bounds: [ref, ref], content_lines: [] },
289
+ fileLines,
290
+ fileHashes,
291
+ [],
292
+ undefined,
293
+ );
294
+ if (mismatches.length > 0 || !resolved) {
295
+ const feedback = fmtMismatchWithHashes(
296
+ mismatches,
297
+ fileLines,
298
+ fileHashes,
299
+ filePath,
300
+ );
301
+ throw new AnchorMismatchError(feedback.text, feedback.hashes, feedback.servedMap);
302
+ }
303
+ return resolved.hash_bounds[0].line;
304
+ }
305
+
306
+ export class RangeStaleError extends Error {
307
+ readonly rangeHashes: string[];
308
+ readonly rangeServedMap: Map<string, string>;
309
+ constructor(message: string, rangeHashes: string[], rangeServedMap: Map<string, string>) {
310
+ super(message);
311
+ this.name = "RangeStaleError";
312
+ this.rangeHashes = rangeHashes;
313
+ this.rangeServedMap = rangeServedMap;
314
+ }
315
+ }
316
+
317
+ export class AnchorMismatchError extends Error {
318
+ readonly feedbackHashes: string[];
319
+ readonly feedbackMap: Map<string, string>;
320
+ constructor(message: string, feedbackHashes: string[], feedbackMap: Map<string, string>) {
321
+ super(message);
322
+ this.name = "AnchorMismatchError";
323
+ this.feedbackHashes = feedbackHashes;
324
+ this.feedbackMap = feedbackMap;
325
+ }
326
+ }
327
+
328
+ export function assertRangeServed(
329
+ resolved: RHEdit,
330
+ fileLines: string[],
331
+ fileHashes: string[],
332
+ served: ReadonlyMap<string, string> | undefined,
333
+ filePath?: string,
334
+ ): void {
335
+ assertAligned(fileLines, fileHashes, "assertRangeServed");
336
+ const startLine = resolved.hash_bounds[0].line;
337
+ const endLine = resolved.hash_bounds[1].line;
338
+ const mismatchLines: number[] = [];
339
+ for (let line = startLine; line <= endLine; line++) {
340
+ const hash = fileHashes[line - 1]!;
341
+ const content = fileLines[line - 1]!;
342
+ const servedContent = served?.get(hash);
343
+ if (servedContent === undefined || servedContent !== lineChecksum(content)) mismatchLines.push(line);
344
+ }
345
+ if (mismatchLines.length === 0) return;
346
+ const rangeLength = endLine - startLine + 1;
347
+ const shownLength = Math.min(rangeLength, MAX_RANGE_STALE_LINES);
348
+ const rows: string[] = [];
349
+ const shownHashes: string[] = [];
350
+ const shownMap = new Map<string, string>();
351
+ for (let line = startLine; line < startLine + shownLength; line++) {
352
+ const hash = fileHashes[line - 1]!;
353
+ const content = fileLines[line - 1]!;
354
+ shownHashes.push(hash);
355
+ shownMap.set(hash, lineChecksum(content));
356
+ rows.push(fmtRow(hash, clipLine(content)));
357
+ }
358
+ const location = filePath ? ` in ${filePath}` : "";
359
+ const first = mismatchLines[0]!;
360
+ const mismatchText =
361
+ mismatchLines.length === 1
362
+ ? `Line ${first} of the replaced range (lines ${startLine}-${endLine})${location} does not match`
363
+ : `${mismatchLines.length} of ${rangeLength} line(s) in the replaced range (lines ${startLine}-${endLine})${location} do not match`;
364
+ const capHint =
365
+ rangeLength > shownLength
366
+ ? `\n\n[The range has ${rangeLength} lines; showing the first ${shownLength}. Call read()${filePath ? ` on ${filePath}` : ""} with offset=${startLine + shownLength} to see the rest.]`
367
+ : "\n\nRetry with the fresh anchors above without a read.";
368
+ const message =
369
+ `[E_RANGE_STALE] ${mismatchText} what was shown. Current range with fresh anchors:\n\n${rows.join("\n")}${capHint}`;
370
+ throw new RangeStaleError(message, shownHashes, shownMap);
371
+ }
372
+
373
+ export { warnUnicodeEsc };
package/src/insert.ts ADDED
@@ -0,0 +1,258 @@
1
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { constants } from "node:fs";
4
+ import { execPipeline, type ReqParams, type ReplaceDetails, previewFromPipe, previewError } from "./replace";
5
+ import { commitEdit } from "./commit";
6
+ import { batchMemberFor, ensureBatchBase, executeBatchMember, noteBatchFailure } from "./batch";
7
+ import { readNormFile, type NormFile } from "./file-reader";
8
+ import { MAX_HASH_LINES, parseHashRef, resEdit, resolveAnchorLine, type Anchor, type HEdit } from "./hashline";
9
+ import { stripAnchorRow } from "./hashline/resolve";
10
+ import { withAnchorSession } from "./anchor-registry";
11
+ import { loadP, loadGuide } from "./prompts";
12
+ import { assertInsertReq, normReq, type InsertReq } from "./payload-contract";
13
+ import { decodeStringArray, isRec, splitLines } from "./utils";
14
+ import { queuedEdit, editToolBase, editRenderCallWrapper, editRenderResultWrapper, resolveEditTargetWithRequirement, throwIfStrictInput, withInsertPrompts, DEFAULT_EDIT_FLAGS, type EditToolFlags } from "./edit-common";
15
+ import type { RPreview, RRState } from "./replace-render";
16
+ export { assertInsertReq, type InsertReq };
17
+
18
+ const insertAnchorSchema = Type.String({
19
+ description:
20
+ 'Bare 4-char anchor from a served anchor│content row (the text before the `│` separator), never the row content. A pasted diff row or `anchor│` prefix is stripped with a warning. The anchor line is preserved; lines go after or before it.',
21
+ });
22
+
23
+ const insertDirectionSchema = Type.Union(
24
+ [Type.Literal("after"), Type.Literal("before")],
25
+ { description: '"after" or "before"' },
26
+ );
27
+
28
+ const insertLinesSchema = Type.Array(
29
+ Type.String({
30
+ description: "One line to insert; never embed \\n inside an element.",
31
+ }),
32
+ {
33
+ description: 'One string per line; [""] is a blank line; never include the anchor line.',
34
+ }
35
+ );
36
+
37
+ const insertPathRequiredSchema = Type.String({
38
+ description:
39
+ "Path to the file the anchor was served for; required and must match anchor ownership. The anchor still resolves the target.",
40
+ });
41
+
42
+ const insertToolSchema = Type.Object(
43
+ {
44
+ anchor: insertAnchorSchema,
45
+ direction: insertDirectionSchema,
46
+ lines: insertLinesSchema,
47
+ },
48
+ { additionalProperties: true },
49
+ );
50
+
51
+ export function buildInsertToolSchema(requirePath: boolean): typeof insertToolSchema {
52
+ if (!requirePath) return insertToolSchema;
53
+ return Type.Object(
54
+ {
55
+ path: insertPathRequiredSchema,
56
+ anchor: insertAnchorSchema,
57
+ direction: insertDirectionSchema,
58
+ lines: insertLinesSchema,
59
+ },
60
+ { additionalProperties: true },
61
+ ) as typeof insertToolSchema;
62
+ }
63
+
64
+ export function parseInsertAnchor(raw: string): { ref: Anchor; warnings: string[] } {
65
+ const trimmedAnchor = raw.trim();
66
+ const warnings: string[] = [];
67
+ const anchorText = stripAnchorRow(trimmedAnchor, "anchor entry", warnings);
68
+ return { ref: parseHashRef(anchorText), warnings };
69
+ }
70
+
71
+ export function buildInsertEdit(
72
+ req: InsertReq,
73
+ preload: NormFile,
74
+ ref: Anchor,
75
+ path: string,
76
+ ): { editParams: ReqParams; anchorLine: string | undefined } {
77
+ const fileLines = splitLines(preload.normalized);
78
+ const line = resolveAnchorLine(ref, fileLines, preload.fileHashes, path);
79
+ const anchorLine = preload.normalized.length === 0 ? undefined : fileLines[line - 1];
80
+ const editParams: ReqParams = {
81
+ remove_from: ref.hash,
82
+ remove_to: ref.hash,
83
+ replacement_lines:
84
+ anchorLine === undefined
85
+ ? [...req.lines]
86
+ : req.direction === "after"
87
+ ? [anchorLine, ...req.lines]
88
+ : [...req.lines, anchorLine],
89
+ };
90
+ return { editParams, anchorLine };
91
+ }
92
+
93
+ export async function insertPreview(request: unknown, cwd: string, signal?: AbortSignal): Promise<RPreview> {
94
+ try {
95
+ const normalized = normReq(request);
96
+ const previewFixes: string[] = [];
97
+ if (isRec(normalized)) {
98
+ const expanded = decodeStringArray(normalized.lines, previewFixes, "lines");
99
+ if (expanded) normalized.lines = expanded;
100
+ }
101
+ assertInsertReq(normalized);
102
+ const previewReq = normalized as InsertReq;
103
+ const { ref, warnings: previewAnchorWarnings } = parseInsertAnchor(previewReq.anchor);
104
+ await throwIfStrictInput([...previewFixes, ...previewAnchorWarnings]);
105
+ const targetPath = await resolveEditTargetWithRequirement({
106
+ anchor: previewReq.anchor,
107
+ providedPath: previewReq.path,
108
+ cwd,
109
+ });
110
+ const preload = await readNormFile(targetPath, cwd, {
111
+ accessMode: constants.R_OK,
112
+ maxLines: MAX_HASH_LINES,
113
+ noPersist: true,
114
+ allocation: "shadow",
115
+ signal,
116
+ });
117
+ const { editParams } = buildInsertEdit(normalized, preload, ref, targetPath);
118
+ const pipe = await execPipeline(targetPath, editParams, cwd, {
119
+ accessMode: constants.R_OK,
120
+ noPersist: true,
121
+ preloadedNorm: preload,
122
+ signal,
123
+ });
124
+ return previewFromPipe(pipe);
125
+ } catch (error: unknown) {
126
+ if (signal?.aborted) throw error;
127
+ return previewError(error);
128
+ }
129
+ }
130
+
131
+ function getInsertInput(args: unknown): { path?: string; anchor?: string; direction?: "before" | "after"; lines?: string[] } | null {
132
+ let normalized: unknown;
133
+ try {
134
+ normalized = normReq(args);
135
+ } catch {
136
+ return null;
137
+ }
138
+ if (!isRec(normalized)) return null;
139
+ if (
140
+ typeof normalized.anchor !== "string" ||
141
+ (normalized.direction !== "before" && normalized.direction !== "after") ||
142
+ !Array.isArray(normalized.lines) ||
143
+ normalized.lines.some((line) => typeof line !== "string")
144
+ ) {
145
+ return null;
146
+ }
147
+ return {
148
+ ...(typeof normalized.path === "string" ? { path: normalized.path } : {}),
149
+ anchor: normalized.anchor as string,
150
+ direction: normalized.direction as "before" | "after",
151
+ lines: normalized.lines as string[],
152
+ };
153
+ }
154
+
155
+ type InsertToolDef = ToolDefinition<any, ReplaceDetails, RRState> & { renderShell?: "default" | "self" };
156
+
157
+ export function buildInsertToolDef(flags: EditToolFlags = DEFAULT_EDIT_FLAGS): InsertToolDef {
158
+ const prompted = withInsertPrompts({
159
+ description: loadP("../prompts/insert.md"),
160
+ snippet: loadP("../prompts/insert-snippet.md"),
161
+ guidelines: loadGuide("../prompts/insert-guidelines.md"),
162
+ }, flags);
163
+ return {
164
+ name: "insert",
165
+ label: "Insert",
166
+ description: prompted.description,
167
+ promptSnippet: prompted.snippet,
168
+ promptGuidelines: prompted.guidelines,
169
+ ...editToolBase,
170
+ parameters: buildInsertToolSchema(flags.requirePath),
171
+ renderCall: editRenderCallWrapper(insertPreview, getInsertInput, "insert"),
172
+ renderResult: editRenderResultWrapper,
173
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
174
+ return withAnchorSession(ctx, async () => {
175
+ const canonical = normReq(params);
176
+ const insertWarnings: string[] = [];
177
+ if (isRec(canonical)) {
178
+ const expanded = decodeStringArray(canonical.lines, insertWarnings, "lines");
179
+ if (expanded) canonical.lines = expanded;
180
+ }
181
+ assertInsertReq(canonical);
182
+ const req = canonical;
183
+ const targetPath = await resolveEditTargetWithRequirement({
184
+ anchor: req.anchor,
185
+ providedPath: req.path,
186
+ cwd: ctx.cwd,
187
+ }).catch((error: unknown) => {
188
+ const member = batchMemberFor(_toolCallId);
189
+ if (member) noteBatchFailure(member, error);
190
+ throw error;
191
+ });
192
+ let ref: Anchor;
193
+ let anchorWarnings: string[];
194
+ try {
195
+ ({ ref, warnings: anchorWarnings } = parseInsertAnchor(req.anchor));
196
+ await throwIfStrictInput([...anchorWarnings, ...insertWarnings]);
197
+ } catch (error) {
198
+ const member = batchMemberFor(_toolCallId);
199
+ if (member) noteBatchFailure(member, error);
200
+ throw error;
201
+ }
202
+ return queuedEdit(targetPath, ctx.cwd, signal, async (absolutePath, mutationTargetPath) => {
203
+ const member = batchMemberFor(_toolCallId);
204
+ if (member) {
205
+ const base = await ensureBatchBase({ member, targetPath, mutationTargetPath, cwd: ctx.cwd, signal });
206
+ const basePreload = { normalized: base.content, fileHashes: base.hashes } as NormFile;
207
+ const built = buildInsertEdit(req, basePreload, ref, targetPath);
208
+ let hedit: HEdit;
209
+ const resWarnings: string[] = [];
210
+ try {
211
+ hedit = resEdit(built.editParams, resWarnings);
212
+ } catch (error) {
213
+ noteBatchFailure(member, error);
214
+ throw error;
215
+ }
216
+ return executeBatchMember({
217
+ kind: "insert",
218
+ direction: req.direction,
219
+ member,
220
+ targetPath,
221
+ mutationTargetPath,
222
+ cwd: ctx.cwd,
223
+ signal,
224
+ hedit,
225
+ extraWarnings: [...anchorWarnings, ...insertWarnings, ...resWarnings],
226
+ foldedLines: built.anchorLine === undefined ? 0 : 1,
227
+ });
228
+ }
229
+ const preload = await readNormFile(targetPath, ctx.cwd, {
230
+ signal,
231
+ accessMode: constants.R_OK | constants.W_OK,
232
+ maxLines: MAX_HASH_LINES,
233
+ });
234
+ const { editParams, anchorLine } = buildInsertEdit(req, preload, ref, targetPath);
235
+ const pipe = await execPipeline(targetPath, editParams, ctx.cwd, {
236
+ accessMode: constants.R_OK | constants.W_OK,
237
+ signal,
238
+ preloadedNorm: preload,
239
+ });
240
+ return commitEdit(pipe, {
241
+ path: pipe.path,
242
+ absolutePath,
243
+ mutationTargetPath,
244
+ signal,
245
+ verb: "inserted",
246
+ noopNoun: "Insertion",
247
+ foldedAnchorLines: anchorLine === undefined ? 0 : 1,
248
+ prefixWarnings: [...anchorWarnings, ...insertWarnings],
249
+ });
250
+ });
251
+ });
252
+ },
253
+ };
254
+ }
255
+
256
+ export function regInsert(pi: ExtensionAPI, flags: EditToolFlags = DEFAULT_EDIT_FLAGS): void {
257
+ pi.registerTool(buildInsertToolDef(flags));
258
+ }
@@ -0,0 +1,27 @@
1
+ export type LineEnding = "\r\n" | "\n" | "\r";
2
+
3
+ export function detectEnding(content: string): LineEnding {
4
+ const crIdx = content.indexOf("\r");
5
+ const lfIdx = content.indexOf("\n");
6
+ if (crIdx === -1 && lfIdx === -1) return "\n";
7
+ if (crIdx === -1) return "\n";
8
+ if (lfIdx === -1) return "\r";
9
+ if (crIdx < lfIdx) return content[crIdx + 1] === "\n" ? "\r\n" : "\r";
10
+ return "\n";
11
+ }
12
+
13
+ export function toLF(text: string): string {
14
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
15
+ }
16
+
17
+ export function restoreEndings(text: string, ending: LineEnding): string {
18
+ if (ending === "\r\n") return text.replace(/\n/g, "\r\n");
19
+ if (ending === "\r") return text.replace(/\n/g, "\r");
20
+ return text;
21
+ }
22
+
23
+ export function stripBOM(content: string): { bom: string; text: string } {
24
+ return content.startsWith("\uFEFF")
25
+ ? { bom: "\uFEFF", text: content.slice(1) }
26
+ : { bom: "", text: content };
27
+ }