@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
package/src/batch.ts ADDED
@@ -0,0 +1,767 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { toDisplayPath } from "./paths";
4
+ import { readConfig, getDiffContextLines } from "./config";
5
+ import { throwIfStrictInput, tryResolveEditTarget } from "./edit-common";
6
+ import { readNormFile, safeSnapId } from "./file-reader";
7
+ import { resolveInCwd, writeAtomic, type FileIdentity } from "./fs-write";
8
+ import {
9
+ AnchorMismatchError,
10
+ RangeStaleError,
11
+ assertNotEmpty,
12
+ changedRange,
13
+ lineHashes,
14
+ planEdit,
15
+ MAX_HASH_LINES,
16
+ type HEdit,
17
+ type PlannedEdit,
18
+ } from "./hashline";
19
+ import { adoptAnchors, servedForPath } from "./anchor-registry";
20
+ import { restoreEndings, stripBOM, toLF, type LineEnding } from "./normalize";
21
+ import { assertInsertReq, assertReq, normReq } from "./payload-contract";
22
+ import { saveUndo } from "./replace-undo";
23
+ import { buildChanged, buildNoop, type RMetrics, type TResult } from "./replace-response";
24
+ import { serveRows, servedHashesFromDiff } from "./served";
25
+ import { abortIf, assertByteLimit, assertLineLimit, errCode, isRec, splitLines } from "./utils";
26
+
27
+ export interface PlannedMember {
28
+ batchKey: number;
29
+ id: string;
30
+ display: number;
31
+ total: number;
32
+ target: string;
33
+ kind: BatchKind;
34
+ args: unknown;
35
+ order: number;
36
+ size: number;
37
+ last: boolean;
38
+ }
39
+
40
+ export type BatchKind = "replace" | "insert";
41
+
42
+ interface BatchBase {
43
+ content: string;
44
+ hashes: string[];
45
+ bom: string;
46
+ ending: LineEnding;
47
+ identity: FileIdentity;
48
+ hadUtf8DecodeErrors: boolean;
49
+ absolutePath: string;
50
+ snapshotId?: string;
51
+ baseLines: string[];
52
+ }
53
+
54
+ export interface BatchPiece {
55
+ order: number;
56
+ kind: BatchKind;
57
+ direction?: "before" | "after";
58
+ start: number;
59
+ end: number;
60
+ fromHash: string;
61
+ toHash: string;
62
+ newLines: string[];
63
+ warnings: string[];
64
+ noop: boolean;
65
+ foldedLines: number;
66
+ }
67
+
68
+ export interface BatchMemberInput {
69
+ kind: BatchKind;
70
+ direction?: "before" | "after";
71
+ member: PlannedMember;
72
+ targetPath: string;
73
+ mutationTargetPath: string;
74
+ cwd: string;
75
+ signal?: AbortSignal;
76
+ hedit: HEdit;
77
+ extraWarnings: string[];
78
+ foldedLines?: number;
79
+ }
80
+
81
+ interface BatchFailure {
82
+ kind: BatchKind;
83
+ order: number;
84
+ code?: string;
85
+ }
86
+
87
+ interface BatchState {
88
+ display: number;
89
+ target: string;
90
+ memberIds: string[];
91
+ replaceCount: number;
92
+ insertCount: number;
93
+ base?: BatchBase;
94
+ paths?: { absolutePath: string; mutationTargetPath: string; displayPath: string };
95
+ served?: ReadonlyMap<string, string>;
96
+ pieces: BatchPiece[];
97
+ applied: number;
98
+ noops: number;
99
+ failures: number;
100
+ failed: boolean;
101
+ firstError?: unknown;
102
+ failure?: BatchFailure;
103
+ warnings: string[];
104
+ }
105
+
106
+ interface EditCall {
107
+ id: string;
108
+ name: string;
109
+ args: unknown;
110
+ }
111
+
112
+ type NormalizedEditArgs =
113
+ | { kind: "replace"; removeFrom: string; removeTo?: string; path?: string }
114
+ | { kind: "insert"; anchor: string; path?: string };
115
+
116
+ const MAX_TRACKED_BATCHES = 256;
117
+
118
+ const plan = new Map<string, PlannedMember>();
119
+ const batches = new Map<number, BatchState>();
120
+ let nextBatchKey = 1;
121
+ const abortedMembers = new Map<string, { display: number; message: string }>();
122
+ const ABORTED_MEMBERS_LIMIT = 1024;
123
+ const placeholderResults = new Map<string, TResult>();
124
+
125
+ function markBatchMembersAborted(runtime: BatchState): void {
126
+ const message = abortedBatchMessage(runtime);
127
+ for (const id of runtime.memberIds) {
128
+ abortedMembers.delete(id);
129
+ abortedMembers.set(id, { display: runtime.display, message });
130
+ const result = placeholderResults.get(id);
131
+ if (result?.details.batch) {
132
+ result.details.batch.aborted = true;
133
+ result.details.batch.abortMessage = message;
134
+ }
135
+ }
136
+ while (abortedMembers.size > ABORTED_MEMBERS_LIMIT) {
137
+ const oldest = abortedMembers.keys().next().value;
138
+ if (oldest === undefined) break;
139
+ abortedMembers.delete(oldest);
140
+ }
141
+ }
142
+
143
+ export function abortedBatchMessageFor(toolCallId: string): string | undefined {
144
+ const marked = abortedMembers.get(toolCallId);
145
+ if (marked !== undefined) return marked.message;
146
+ const member = plan.get(toolCallId);
147
+ if (!member) return undefined;
148
+ const runtime = batches.get(member.batchKey);
149
+ return runtime?.failed ? abortedBatchMessage(runtime) : undefined;
150
+ }
151
+
152
+ export function batchMemberFor(toolCallId: string): PlannedMember | undefined {
153
+ return plan.get(toolCallId);
154
+ }
155
+
156
+ export function resetBatchStateForTests(): void {
157
+ plan.clear();
158
+ batches.clear();
159
+ abortedMembers.clear();
160
+ placeholderResults.clear();
161
+ nextBatchKey = 1;
162
+ }
163
+
164
+ function normalizeEditArgs(args: unknown): NormalizedEditArgs | undefined {
165
+ if (!isRec(args)) return undefined;
166
+ const normalized = normReq(args);
167
+ if (!isRec(normalized)) return undefined;
168
+ const path = typeof normalized.path === "string" ? normalized.path : undefined;
169
+ if (typeof normalized.remove_from === "string") {
170
+ return {
171
+ kind: "replace",
172
+ removeFrom: normalized.remove_from,
173
+ ...(typeof normalized.remove_to === "string" ? { removeTo: normalized.remove_to } : {}),
174
+ ...(path ? { path } : {}),
175
+ };
176
+ }
177
+ if (typeof normalized.anchor === "string") {
178
+ return { kind: "insert", anchor: normalized.anchor, ...(path ? { path } : {}) };
179
+ }
180
+ return undefined;
181
+ }
182
+
183
+ async function verifyPaths(
184
+ group: Array<{ id: string; target: string; kind: BatchKind; args: unknown; path?: string }>,
185
+ cwd: string,
186
+ ): Promise<Array<{ id: string; target: string; kind: BatchKind; args: unknown; path?: string }>> {
187
+ const verified: Array<{ id: string; target: string; kind: BatchKind; args: unknown; path?: string }> = [];
188
+ for (const item of group) {
189
+ if (!item.path) continue;
190
+ let resolved: string | undefined;
191
+ try {
192
+ resolved = (await resolveInCwd(item.path, cwd)).resolved;
193
+ } catch {
194
+ resolved = undefined;
195
+ }
196
+ if (resolved === item.target) verified.push(item);
197
+ }
198
+ return verified;
199
+ }
200
+
201
+ function enforceCap(): void {
202
+ while (batches.size > MAX_TRACKED_BATCHES) {
203
+ const oldest = batches.keys().next().value;
204
+ if (oldest === undefined) return;
205
+ const state = batches.get(oldest);
206
+ batches.delete(oldest);
207
+ if (state) {
208
+ for (const id of state.memberIds) {
209
+ plan.delete(id);
210
+ placeholderResults.delete(id);
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ export async function planAssistantMessage(message: unknown, cwd: string): Promise<void> {
217
+ if (!isRec(message) || message.role !== "assistant" || !Array.isArray(message.content)) return;
218
+ const calls: EditCall[] = [];
219
+ for (const block of message.content) {
220
+ if (!isRec(block) || block.type !== "toolCall") continue;
221
+ if (block.name !== "replace" && block.name !== "insert") continue;
222
+ if (typeof block.id !== "string") continue;
223
+ calls.push({ id: block.id, name: block.name, args: block.arguments });
224
+ }
225
+ if (calls.length < 2) return;
226
+ const earlyConfig = await readConfig();
227
+ const requirePath = earlyConfig.requirePath === true;
228
+ interface ResolvedCall { id: string; target: string; kind: BatchKind; args: unknown; path?: string }
229
+ const resolved: ResolvedCall[] = [];
230
+ for (const call of calls) {
231
+ const normalized = normalizeEditArgs(call.args);
232
+ if (!normalized) continue;
233
+ let target = normalized.kind === "replace" ? tryResolveEditTarget(normalized.removeFrom, normalized.removeTo) : tryResolveEditTarget(normalized.anchor);
234
+ if (!target) {
235
+ if (requirePath && normalized.path) {
236
+ try {
237
+ target = (await resolveInCwd(normalized.path, cwd)).resolved;
238
+ } catch {
239
+ target = undefined;
240
+ }
241
+ } else if (normalized.kind === "replace") {
242
+ target = tryResolveEditTarget(normalized.removeFrom) ?? (normalized.removeTo ? tryResolveEditTarget(normalized.removeTo) : undefined);
243
+ }
244
+ }
245
+ if (target) resolved.push({ id: call.id, target, kind: call.name as BatchKind, args: call.args, ...(normalized.path ? { path: normalized.path } : {}) });
246
+ }
247
+ const groups = new Map<string, ResolvedCall[]>();
248
+ for (const item of resolved) {
249
+ const group = groups.get(item.target) ?? [];
250
+ group.push(item);
251
+ groups.set(item.target, group);
252
+ }
253
+ const multi = [...groups.values()].filter((group) => group.length >= 2);
254
+ const finalGroups: ResolvedCall[][] = [];
255
+ if (requirePath) {
256
+ for (const group of multi) {
257
+ const verified = await verifyPaths(group, cwd);
258
+ if (verified.length >= 2) finalGroups.push(verified);
259
+ }
260
+ } else {
261
+ finalGroups.push(...multi);
262
+ }
263
+ let display = 0;
264
+ for (const group of finalGroups) {
265
+ display += 1;
266
+ const key = nextBatchKey++;
267
+ batches.set(key, {
268
+ display,
269
+ target: group[0]!.target,
270
+ memberIds: group.map((item) => item.id),
271
+ replaceCount: 0,
272
+ insertCount: 0,
273
+ pieces: [],
274
+ applied: 0,
275
+ noops: 0,
276
+ failures: 0,
277
+ failed: false,
278
+ warnings: [],
279
+ });
280
+ group.forEach((item, index) => {
281
+ plan.set(item.id, {
282
+ batchKey: key,
283
+ id: item.id,
284
+ display,
285
+ total: finalGroups.length,
286
+ target: item.target,
287
+ kind: item.kind,
288
+ args: item.args,
289
+ order: index + 1,
290
+ size: group.length,
291
+ last: index === group.length - 1,
292
+ });
293
+ });
294
+ enforceCap();
295
+ }
296
+ }
297
+
298
+ function dedupeWarnings(warnings: string[]): string[] {
299
+ const seen = new Set<string>();
300
+ const out: string[] = [];
301
+ for (const warning of warnings) {
302
+ if (seen.has(warning)) continue;
303
+ seen.add(warning);
304
+ out.push(warning);
305
+ }
306
+ return out;
307
+ }
308
+
309
+ function batchVerb(runtime: BatchState): string {
310
+ if (runtime.replaceCount > 0 && runtime.insertCount > 0) return "edited";
311
+ if (runtime.insertCount > 0) return "inserted";
312
+ return "replaced";
313
+ }
314
+ function batchHeader(member: PlannedMember): string {
315
+ return `batch ${member.display}:`;
316
+ }
317
+
318
+ function formatBatchLines(start: number, end: number): string {
319
+ return start === end ? `line ${start}` : `lines ${start}-${end}`;
320
+ }
321
+
322
+ function formatBatchPiece(piece: BatchPiece): string {
323
+ const lines = formatBatchLines(piece.start, piece.end);
324
+ if (piece.kind === "insert") return `edit #${piece.order} (insert at ${piece.fromHash}, ${lines})`;
325
+ if (piece.fromHash === piece.toHash) return `edit #${piece.order} (replace ${piece.fromHash}, ${lines})`;
326
+ return `edit #${piece.order} (replace ${piece.fromHash}→${piece.toHash}, ${lines})`;
327
+ }
328
+
329
+ function batchPlaceholder(member: PlannedMember, piece: BatchPiece, snapshotId: string | undefined): TResult {
330
+ const added = piece.kind === "insert" ? Math.max(0, piece.newLines.length - piece.foldedLines) : piece.newLines.length;
331
+ const metrics: RMetrics = {
332
+ edits_attempted: 1,
333
+ edits_noop: piece.noop ? 1 : 0,
334
+ warnings: 0,
335
+ classification: piece.noop ? "noop" : "applied",
336
+ ...(piece.noop ? {} : { added_lines: added, removed_lines: piece.end - piece.start + 1 }),
337
+ };
338
+ return {
339
+ content: [
340
+ {
341
+ type: "text",
342
+ text: `In batch ${member.display}`,
343
+ },
344
+ ],
345
+ details: {
346
+ diff: "",
347
+ patch: "",
348
+ ...(piece.noop ? {} : { firstChangedLine: piece.start }),
349
+ ...(snapshotId !== undefined ? { snapshotId } : {}),
350
+ ...(piece.noop ? { classification: "noop" as const } : {}),
351
+ metrics,
352
+ batch: { id: member.display, size: member.size, last: false, total: member.total },
353
+ },
354
+ };
355
+ }
356
+
357
+ export function withAbortSuffix(message: string, display: number): string {
358
+ const suffix = `Aborts batch ${display}.`;
359
+ if (message.includes(suffix)) return message;
360
+ return message.endsWith(".") ? `${message} ${suffix}` : `${message}. ${suffix}`;
361
+ }
362
+
363
+ const ERROR_CODE_RE = /\[(E_[A-Z0-9_]+)\]/;
364
+
365
+ function errorCodeOf(error: unknown): string | undefined {
366
+ if (!(error instanceof Error)) return undefined;
367
+ const code = ERROR_CODE_RE.exec(error.message)?.[1];
368
+ return code === "E_OP_ABORTED" ? undefined : code;
369
+ }
370
+
371
+ export function noteBatchFailure(member: PlannedMember, error: unknown): void {
372
+ const runtime = batches.get(member.batchKey);
373
+ if (!runtime) return;
374
+ if (error instanceof Error && !error.message.startsWith("[E_OP_ABORTED]")) error.message = withAbortSuffix(error.message, member.display);
375
+ runtime.failures += 1;
376
+ if (!runtime.failed) {
377
+ runtime.failed = true;
378
+ runtime.firstError = error;
379
+ const code = errorCodeOf(error);
380
+ runtime.failure = { kind: member.kind, order: member.order, ...(code !== undefined ? { code } : {}) };
381
+ }
382
+ markBatchMembersAborted(runtime);
383
+ }
384
+
385
+ function firstFailureCause(runtime: BatchState): string | undefined {
386
+ const error = runtime.firstError;
387
+ if (!(error instanceof Error)) return undefined;
388
+ const suffix = ` Aborts batch ${runtime.display}.`;
389
+ const message = error.message.endsWith(suffix) ? error.message.slice(0, -suffix.length) : error.message;
390
+ const firstLine = message.split("\n")[0]?.trim() ?? "";
391
+ if (firstLine.length === 0) return undefined;
392
+ if (!firstLine.endsWith(":")) return firstLine;
393
+ const sentenceEnd = firstLine.lastIndexOf(". ");
394
+ return sentenceEnd >= 0 ? firstLine.slice(0, sentenceEnd + 1) : firstLine.slice(0, -1);
395
+ }
396
+
397
+ function abortedBatchMessage(runtime: BatchState): string {
398
+ const failure = runtime.failure;
399
+ if (failure?.code !== undefined) {
400
+ return `[E_OP_ABORTED] Batch ${runtime.display} aborted: [${failure.kind}] Call Nr ${failure.order} errored [${failure.code}]`;
401
+ }
402
+ const cause = firstFailureCause(runtime);
403
+ return cause ? `[E_OP_ABORTED] Batch ${runtime.display} aborted: ${cause}` : `[E_OP_ABORTED] Batch ${runtime.display} aborted.`;
404
+ }
405
+
406
+ function batchAbortedError(runtime: BatchState): Error {
407
+ discardBatchState(runtime);
408
+ return new Error(abortedBatchMessage(runtime));
409
+ }
410
+ function discardBatchState(runtime: BatchState): void {
411
+ markBatchMembersAborted(runtime);
412
+ }
413
+
414
+ export async function ensureBatchBase(input: {
415
+ member: PlannedMember;
416
+ targetPath: string;
417
+ mutationTargetPath: string;
418
+ cwd: string;
419
+ signal?: AbortSignal;
420
+ }): Promise<BatchBase> {
421
+ const runtime = batches.get(input.member.batchKey);
422
+ if (!runtime) throw new Error(`[E_STALE_ANCHOR] Batch ${input.member.display} is no longer tracked. Call read for fresh anchors.`);
423
+ if (runtime.base) return runtime.base;
424
+ abortIf(input.signal);
425
+ const file = await readNormFile(input.targetPath, input.cwd, {
426
+ signal: input.signal,
427
+ accessMode: constants.R_OK | constants.W_OK,
428
+ maxLines: MAX_HASH_LINES,
429
+ });
430
+ const snapshotId = await safeSnapId(file.absolutePath, "batch edit");
431
+ const base: BatchBase = {
432
+ content: file.normalized,
433
+ hashes: file.fileHashes.slice(),
434
+ bom: file.bom,
435
+ ending: file.originalEnding,
436
+ identity: file.identity,
437
+ hadUtf8DecodeErrors: file.hadUtf8DecodeErrors,
438
+ absolutePath: file.absolutePath,
439
+ ...(snapshotId !== undefined ? { snapshotId } : {}),
440
+ baseLines: splitLines(file.normalized),
441
+ };
442
+ runtime.base = base;
443
+ runtime.served = servedForPath(file.absolutePath);
444
+ runtime.paths = {
445
+ absolutePath: file.absolutePath,
446
+ mutationTargetPath: input.mutationTargetPath,
447
+ displayPath: toDisplayPath(input.cwd, file.absolutePath, input.targetPath),
448
+ };
449
+ return base;
450
+ }
451
+
452
+ export async function executeBatchMember(input: BatchMemberInput): Promise<TResult> {
453
+ const runtime = batches.get(input.member.batchKey);
454
+ if (!runtime) throw new Error(`[E_STALE_ANCHOR] Batch ${input.member.display} is no longer tracked. Call read for fresh anchors.`);
455
+ if (runtime.failed) throw batchAbortedError(runtime);
456
+ let base: BatchBase;
457
+ try {
458
+ base = await ensureBatchBase({
459
+ member: input.member,
460
+ targetPath: input.targetPath,
461
+ mutationTargetPath: input.mutationTargetPath,
462
+ cwd: input.cwd,
463
+ signal: input.signal,
464
+ });
465
+ } catch (error) {
466
+ noteBatchFailure(input.member, error);
467
+ discardBatchState(runtime);
468
+ throw error;
469
+ }
470
+ if (input.mutationTargetPath !== input.member.target) {
471
+ const error = new Error(`[E_STALE_ANCHOR] "${input.hedit.hash_bounds[0].hash}" is no longer owned by ${input.member.target}. Call read for fresh anchors.`);
472
+ noteBatchFailure(input.member, error);
473
+ discardBatchState(runtime);
474
+ throw error;
475
+ }
476
+ const displayPath = runtime.paths?.displayPath ?? input.targetPath;
477
+ let planned: PlannedEdit;
478
+ try {
479
+ planned = planEdit(base.content, input.hedit, base.hashes, {
480
+ filePath: displayPath,
481
+ servedHashes: runtime.served,
482
+ signal: input.signal,
483
+ baseFileLines: base.baseLines,
484
+ });
485
+ } catch (error) {
486
+ if (error instanceof RangeStaleError) adoptAnchors(base.absolutePath, error.rangeServedMap);
487
+ else if (error instanceof AnchorMismatchError) adoptAnchors(base.absolutePath, error.feedbackMap);
488
+ noteBatchFailure(input.member, error);
489
+ discardBatchState(runtime);
490
+ throw error;
491
+ }
492
+ const start = planned.resolved.hash_bounds[0].line;
493
+ const end = planned.resolved.hash_bounds[1].line;
494
+ const newLines = planned.resolved.content_lines;
495
+ const baseLines = base.baseLines;
496
+ const originalSlice = baseLines.slice(start - 1, end);
497
+ const noop = originalSlice.length === newLines.length && originalSlice.every((line, index) => line === newLines[index]);
498
+ const piece: BatchPiece = {
499
+ order: input.member.order,
500
+ kind: input.kind,
501
+ ...(input.direction !== undefined ? { direction: input.direction } : {}),
502
+ start,
503
+ end,
504
+ fromHash: input.hedit.hash_bounds[0].hash,
505
+ toHash: input.hedit.hash_bounds[1].hash,
506
+ newLines: [...newLines],
507
+ warnings: [...input.extraWarnings, ...planned.warnings],
508
+ noop,
509
+ foldedLines: input.foldedLines ?? 0,
510
+ };
511
+ runtime.pieces.push(piece);
512
+ if (input.kind === "replace") runtime.replaceCount += 1;
513
+ else runtime.insertCount += 1;
514
+ if (noop) runtime.noops += 1;
515
+ else runtime.applied += 1;
516
+ runtime.warnings.push(...piece.warnings);
517
+ if (!input.member.last) {
518
+ const placeholder = batchPlaceholder(input.member, piece, base.snapshotId);
519
+ placeholderResults.set(input.member.id, placeholder);
520
+ return placeholder;
521
+ }
522
+ return finishBatch(input.member, input.signal);
523
+ }
524
+
525
+ function composeBatchLines(baseContent: string, pieces: BatchPiece[]): string {
526
+ const lines = splitLines(baseContent);
527
+ const descending = [...pieces].sort((a, b) => b.start - a.start);
528
+ for (const piece of descending) lines.splice(piece.start - 1, piece.end - piece.start + 1, ...piece.newLines);
529
+ let composed = lines.join("\n");
530
+ if (lines.length > 0 && (baseContent.endsWith("\n") || lines[lines.length - 1] === "")) composed += "\n";
531
+ return composed;
532
+ }
533
+
534
+ function mergeInsertPairs(pieces: BatchPiece[]): BatchPiece[] {
535
+ const byAnchor = new Map<number, BatchPiece[]>();
536
+ for (const piece of pieces) {
537
+ if (piece.kind !== "insert" || piece.start !== piece.end || piece.foldedLines === 0) continue;
538
+ const group = byAnchor.get(piece.start) ?? [];
539
+ group.push(piece);
540
+ byAnchor.set(piece.start, group);
541
+ }
542
+ const partnerOf = new Map<BatchPiece, BatchPiece>();
543
+ for (const group of byAnchor.values()) {
544
+ if (group.length !== 2) continue;
545
+ const [first, second] = group;
546
+ if (first.direction === undefined || second.direction === undefined || first.direction === second.direction) continue;
547
+ partnerOf.set(first, second);
548
+ partnerOf.set(second, first);
549
+ }
550
+ const merged: BatchPiece[] = [];
551
+ const consumed = new Set<BatchPiece>();
552
+ for (const piece of pieces) {
553
+ if (consumed.has(piece)) continue;
554
+ const partner = partnerOf.get(piece);
555
+ if (partner === undefined) {
556
+ merged.push(piece);
557
+ continue;
558
+ }
559
+ consumed.add(piece);
560
+ consumed.add(partner);
561
+ const before = piece.direction === "before" ? piece : partner;
562
+ const after = piece.direction === "before" ? partner : piece;
563
+ merged.push({
564
+ ...before,
565
+ order: Math.min(before.order, after.order),
566
+ newLines: [...before.newLines, ...after.newLines.slice(1)],
567
+ warnings: [...before.warnings, ...after.warnings],
568
+ foldedLines: before.foldedLines + after.foldedLines - 1,
569
+ });
570
+ }
571
+ return merged;
572
+ }
573
+
574
+ async function finishBatch(member: PlannedMember, signal?: AbortSignal): Promise<TResult> {
575
+ const runtime = batches.get(member.batchKey);
576
+ if (!runtime || !runtime.base || !runtime.paths) throw new Error(`[E_STALE_ANCHOR] Batch ${member.display} is no longer tracked. Call read for fresh anchors.`);
577
+ const base = runtime.base;
578
+ const paths = runtime.paths;
579
+ if (runtime.failed) throw batchAbortedError(runtime);
580
+ const executedOrders = new Set(runtime.pieces.map((piece) => piece.order));
581
+ for (const id of runtime.memberIds) {
582
+ const planned = plan.get(id);
583
+ if (!planned) continue;
584
+ if (executedOrders.has(planned.order)) continue;
585
+ try {
586
+ const normalized = normReq(planned.args);
587
+ if (planned.kind === "replace") assertReq(normalized);
588
+ else assertInsertReq(normalized);
589
+ } catch (error) {
590
+ noteBatchFailure(planned, error);
591
+ throw batchAbortedError(runtime);
592
+ }
593
+ }
594
+ const appliedPieces = runtime.pieces.filter((piece) => !piece.noop);
595
+ if (appliedPieces.length === 0) {
596
+ const snapshotId = await safeSnapId(paths.absolutePath, "noop edit");
597
+ return combinedNoop(paths.displayPath, member, runtime, snapshotId);
598
+ }
599
+ const effectivePieces = mergeInsertPairs(appliedPieces);
600
+ const ordered = [...effectivePieces].sort((a, b) => a.start - b.start);
601
+ for (let i = 1; i < ordered.length; i++) {
602
+ const prev = ordered[i - 1]!;
603
+ const current = ordered[i]!;
604
+ if (current.start <= prev.end) {
605
+ discardBatchState(runtime);
606
+ throw new Error(`[E_BATCH_OVERLAP] Batch ${runtime.display} has overlapping ranges: ${formatBatchPiece(prev)} overlaps ${formatBatchPiece(current)}`);
607
+ }
608
+ }
609
+ const composed = composeBatchLines(base.content, effectivePieces);
610
+ const warnings = [...runtime.warnings];
611
+ if (base.hadUtf8DecodeErrors) warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
612
+ try {
613
+ await throwIfStrictInput(dedupeWarnings(warnings));
614
+ assertNotEmpty(base.content, composed);
615
+ assertLineLimit(composed, paths.displayPath, MAX_HASH_LINES);
616
+ const finalBytes = base.bom + restoreEndings(composed, base.ending);
617
+ assertByteLimit(finalBytes, paths.displayPath);
618
+ } catch (error) {
619
+ discardBatchState(runtime);
620
+ if (error instanceof Error) error.message = withAbortSuffix(error.message, runtime.display);
621
+ throw error;
622
+ }
623
+ if (composed === base.content) {
624
+ const snapshotId = await safeSnapId(paths.absolutePath, "noop edit");
625
+ return combinedNoop(paths.displayPath, member, runtime, snapshotId);
626
+ }
627
+ abortIf(signal);
628
+ let currentRaw: string;
629
+ try {
630
+ currentRaw = await readFile(runtime.target, "utf-8");
631
+ } catch (error) {
632
+ if (errCode(error) !== "ENOENT") throw error;
633
+ discardBatchState(runtime);
634
+ throw new Error(`[E_OP_ABORTED] Batch ${runtime.display} aborted: the file was deleted after the batch started.`);
635
+ }
636
+ if (toLF(stripBOM(currentRaw).text) !== base.content) {
637
+ discardBatchState(runtime);
638
+ throw new Error(`[E_OP_ABORTED] Batch ${runtime.display} aborted: the file changed after the batch started. Call read for fresh anchors and retry.`);
639
+ }
640
+ const preflightSpans = effectivePieces.map((piece) => ({ start: piece.start - 1, end: piece.end - 1, replacementCount: piece.newLines.length }));
641
+ try {
642
+ await lineHashes(composed, runtime.target, {
643
+ content: base.content,
644
+ hashes: base.hashes,
645
+ spans: preflightSpans,
646
+ }, undefined, false, true);
647
+ } catch (error) {
648
+ discardBatchState(runtime);
649
+ if (error instanceof Error) error.message = withAbortSuffix(error.message, runtime.display);
650
+ throw error;
651
+ }
652
+ const undo = await saveUndo(runtime.target, {
653
+ content: base.content,
654
+ bom: base.bom,
655
+ originalEnding: base.ending,
656
+ hashes: base.hashes,
657
+ resultContent: composed,
658
+ });
659
+ if (!undo.persisted) {
660
+ discardBatchState(runtime);
661
+ throw new Error(`[E_UNDO_UNAVAILABLE] Could not persist undo history for ${paths.displayPath}. Aborts batch ${runtime.display}.`);
662
+ }
663
+ try {
664
+ abortIf(signal);
665
+ await writeAtomic(paths.absolutePath, base.bom + restoreEndings(composed, base.ending), base.identity);
666
+ } catch (error) {
667
+ await undo.restore();
668
+ discardBatchState(runtime);
669
+ if (error instanceof Error) error.message = withAbortSuffix(error.message, runtime.display);
670
+ throw error;
671
+ }
672
+ const updatedSnapshotId = await safeSnapId(paths.absolutePath, "post-edit");
673
+ const spans = effectivePieces.map((piece) => ({ start: piece.start - 1, end: piece.end - 1, replacementCount: piece.newLines.length }));
674
+ let resultHashes: string[];
675
+ try {
676
+ resultHashes = await lineHashes(composed, runtime.target, {
677
+ content: base.content,
678
+ hashes: base.hashes,
679
+ spans,
680
+ });
681
+ } catch (error) {
682
+ const detail = error instanceof Error ? error.message : String(error);
683
+ throw new Error(`${detail} File was written; anchor finalization failed. One undo reverts. Call read for fresh anchors.`);
684
+ }
685
+ const range = changedRange(base.content, composed);
686
+ let added = 0;
687
+ let removed = 0;
688
+ for (const piece of appliedPieces) {
689
+ removed += piece.end - piece.start + 1;
690
+ added += piece.kind === "insert" ? Math.max(0, piece.newLines.length - piece.foldedLines) : piece.newLines.length;
691
+ }
692
+ const header = batchHeader(member);
693
+ const changed = buildChanged(
694
+ {
695
+ path: paths.displayPath,
696
+ originalNormalized: base.content,
697
+ originalHashes: base.hashes,
698
+ result: composed,
699
+ resultHashes,
700
+ warnings: dedupeWarnings(warnings),
701
+ snapshotId: updatedSnapshotId,
702
+ editMeta: {
703
+ editsAttempted: runtime.applied + runtime.noops,
704
+ noopEditsCount: runtime.noops,
705
+ firstChangedLine: range?.firstChangedLine,
706
+ lastChangedLine: range?.lastChangedLine,
707
+ addedLines: added,
708
+ removedLines: removed,
709
+ },
710
+ spans,
711
+ },
712
+ batchVerb(runtime),
713
+ await getDiffContextLines(),
714
+ );
715
+ changed.details.diff = `${header}\n${changed.details.diff}`;
716
+ changed.details.diffLineNumbers?.unshift(null);
717
+ try {
718
+ serveRows(runtime.target, resultHashes, splitLines(composed), servedHashesFromDiff(changed.details.diff));
719
+ } catch (error) {
720
+ console.error("Failed to mark batch diff served:", error);
721
+ }
722
+ const executed = runtime.applied + runtime.noops;
723
+ changed.content[0]!.text = `${header}\n${changed.content[0]!.text}\nBatch ${member.display}: ${executed} edit${executed === 1 ? "" : "s"} applied as one commit; one undo reverts them.`;
724
+ changed.details.batch = { id: member.display, size: member.size, last: true, total: member.total };
725
+ return changed;
726
+ }
727
+
728
+ async function combinedNoop(path: string, member: PlannedMember, runtime: BatchState, snapshotId: string | undefined): Promise<TResult> {
729
+ const executed = runtime.applied + runtime.noops;
730
+ const warnings = [...runtime.warnings];
731
+ const noop = buildNoop(
732
+ {
733
+ path,
734
+ noopEdit: undefined,
735
+ snapshotId,
736
+ editMeta: {
737
+ editsAttempted: executed,
738
+ noopEditsCount: runtime.noops,
739
+ addedLines: 0,
740
+ removedLines: 0,
741
+ },
742
+ warnings: dedupeWarnings(warnings),
743
+ },
744
+ "Batch",
745
+ );
746
+ noop.content[0]!.text += `\nBatch ${member.display}: ${executed} edits produced no net change; undo history preserved.`;
747
+ noop.details.batch = { id: member.display, size: member.size, last: true, total: member.total };
748
+ return noop;
749
+ }
750
+
751
+
752
+ export async function finalizeTurn(toolCallIds: string[]): Promise<void> {
753
+ const keys = new Set<number>();
754
+ for (const id of toolCallIds) {
755
+ const member = plan.get(id);
756
+ if (member) keys.add(member.batchKey);
757
+ }
758
+ for (const key of keys) {
759
+ const runtime = batches.get(key);
760
+ if (!runtime) continue;
761
+ for (const id of runtime.memberIds) {
762
+ plan.delete(id);
763
+ placeholderResults.delete(id);
764
+ }
765
+ batches.delete(key);
766
+ }
767
+ }