@criogaid/pi-hashline-edit 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
package/src/core/apply.ts CHANGED
@@ -28,15 +28,28 @@
28
28
  */
29
29
 
30
30
  import { computeLineHash } from "./hash.ts";
31
- import { detectLineEnding, hasFinalNewline, lineSeparators, replacementSeparator, splitLines } from "./lines.ts";
32
- import type { Anchor, AnchorCheck, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
31
+ import {
32
+ detectLineEnding,
33
+ hasFinalNewline,
34
+ lineSeparators,
35
+ replacementSeparator,
36
+ splitLines,
37
+ } from "./lines.ts";
38
+ import type {
39
+ Anchor,
40
+ AnchorCheck,
41
+ AnchorFailure,
42
+ AnchorRecovery,
43
+ ApplyResult,
44
+ Edit,
45
+ } from "./types.ts";
33
46
  import { findSortedRangeConflict } from "./ranges.ts";
34
47
 
35
48
  /** Line-level operation: replace the raw lines in the `[lo, hi)` range (0-based, hi exclusive) with newLines. */
36
49
  interface SpanOp {
37
- lo: number;
38
- hi: number;
39
- newLines: string[];
50
+ lo: number;
51
+ hi: number;
52
+ newLines: string[];
40
53
  }
41
54
 
42
55
  /** Default first-pass ±line radius before full-file recovery. */
@@ -55,130 +68,152 @@ const DEFAULT_SHIFT_RADIUS = 15;
55
68
  * hash computed for that line, so it verifies on retry.
56
69
  */
57
70
  function verifyAnchor(
58
- lines: readonly string[],
59
- cited: Anchor,
60
- which: "anchor" | "end",
61
- opIndex: number,
62
- op: Edit["op"],
63
- hashLen: number,
64
- radius: number,
71
+ lines: readonly string[],
72
+ cited: Anchor,
73
+ which: "anchor" | "end",
74
+ opIndex: number,
75
+ op: Edit["op"],
76
+ hashLen: number,
77
+ radius: number,
65
78
  ): AnchorFailure | null {
66
- const { line, hash } = cited;
67
- if (line >= 1 && line <= lines.length && computeLineHash(line, lines[line - 1], hashLen) === hash) {
68
- return null;
69
- }
79
+ const { line, hash } = cited;
80
+ if (
81
+ line >= 1 &&
82
+ line <= lines.length &&
83
+ computeLineHash(line, lines[line - 1], hashLen) === hash
84
+ ) {
85
+ return null;
86
+ }
70
87
 
71
- const candidates: { line: number; hash: string }[] = [];
72
- let scope: "local" | "full-file" = "local";
73
- const scan = (start: number, end: number) => {
74
- for (let c = start; c <= end; c++) {
75
- if (c === line) continue;
76
- if (computeLineHash(line, lines[c - 1], hashLen) === hash) {
77
- candidates.push({ line: c, hash: computeLineHash(c, lines[c - 1], hashLen) });
78
- }
79
- }
80
- };
81
- if (radius > 0) {
82
- const lo = Math.max(1, line - radius);
83
- const hi = Math.min(lines.length, line + radius);
84
- scan(lo, hi);
85
- // Preserve local candidates; scan both remaining regions before deciding uniqueness.
86
- if (candidates.length === 0) {
87
- scope = "full-file";
88
- scan(1, Math.min(lines.length, lo - 1));
89
- scan(Math.max(1, hi + 1), lines.length);
90
- }
91
- }
88
+ const candidates: { line: number; hash: string }[] = [];
89
+ let scope: "local" | "full-file" = "local";
90
+ const scan = (start: number, end: number) => {
91
+ for (let c = start; c <= end; c++) {
92
+ if (c === line) continue;
93
+ if (computeLineHash(line, lines[c - 1], hashLen) === hash) {
94
+ candidates.push({ line: c, hash: computeLineHash(c, lines[c - 1], hashLen) });
95
+ }
96
+ }
97
+ };
98
+ if (radius > 0) {
99
+ const lo = Math.max(1, line - radius);
100
+ const hi = Math.min(lines.length, line + radius);
101
+ scan(lo, hi);
102
+ // Preserve local candidates; scan both remaining regions before deciding uniqueness.
103
+ if (candidates.length === 0) {
104
+ scope = "full-file";
105
+ scan(1, Math.min(lines.length, lo - 1));
106
+ scan(Math.max(1, hi + 1), lines.length);
107
+ }
108
+ }
92
109
 
93
- let recovery: AnchorRecovery;
94
- if (candidates.length === 1) {
95
- recovery = { kind: "found", scope, newLine: candidates[0].line, newHash: candidates[0].hash };
96
- } else if (candidates.length > 1) {
97
- recovery = { kind: "ambiguous", scope, candidates };
98
- } else {
99
- recovery = { kind: "none" };
100
- }
110
+ let recovery: AnchorRecovery;
111
+ if (candidates.length === 1) {
112
+ recovery = { kind: "found", scope, newLine: candidates[0].line, newHash: candidates[0].hash };
113
+ } else if (candidates.length > 1) {
114
+ recovery = { kind: "ambiguous", scope, candidates };
115
+ } else {
116
+ recovery = { kind: "none" };
117
+ }
101
118
 
102
- const current =
103
- line >= 1 && line <= lines.length
104
- ? { hash: computeLineHash(line, lines[line - 1], hashLen), content: lines[line - 1] }
105
- : null;
119
+ const current =
120
+ line >= 1 && line <= lines.length
121
+ ? { hash: computeLineHash(line, lines[line - 1], hashLen), content: lines[line - 1] }
122
+ : null;
106
123
 
107
- return { opIndex, which, op, cited, recovery, current };
124
+ return { opIndex, which, op, cited, recovery, current };
108
125
  }
109
126
 
110
127
  type TranslateResult =
111
- | { readonly ok: true; readonly op: SpanOp; readonly checks: AnchorCheck[] }
112
- | { readonly ok: false; readonly anchorFailures: AnchorFailure[]; readonly checks: AnchorCheck[] }
113
- | { readonly ok: false; readonly rangeError: string; readonly checks: AnchorCheck[] };
128
+ | { readonly ok: true; readonly op: SpanOp; readonly checks: AnchorCheck[] }
129
+ | { readonly ok: false; readonly anchorFailures: AnchorFailure[]; readonly checks: AnchorCheck[] }
130
+ | { readonly ok: false; readonly rangeError: string; readonly checks: AnchorCheck[] };
114
131
 
115
- function checkedAnchor(edit: Edit, opIndex: number, which: "anchor" | "end", cited: Anchor, failure: AnchorFailure | null): AnchorCheck {
116
- return { opIndex, which, op: edit.op, cited, status: failure ? "mismatched" : "matched" };
132
+ function checkedAnchor(
133
+ edit: Edit,
134
+ opIndex: number,
135
+ which: "anchor" | "end",
136
+ cited: Anchor,
137
+ failure: AnchorFailure | null,
138
+ ): AnchorCheck {
139
+ return { opIndex, which, op: edit.op, cited, status: failure ? "mismatched" : "matched" };
117
140
  }
118
141
 
119
142
  function inputAnchorChecks(edits: readonly Edit[], status: AnchorCheck["status"]): AnchorCheck[] {
120
- const checks: AnchorCheck[] = [];
121
- for (let opIndex = 0; opIndex < edits.length; opIndex++) {
122
- const edit = edits[opIndex];
123
- if (edit.op === "replace" || edit.op === "delete") {
124
- checks.push({ opIndex, which: "anchor", op: edit.op, cited: edit.start, status });
125
- if (edit.end) checks.push({ opIndex, which: "end", op: edit.op, cited: edit.end, status });
126
- } else if (edit.op === "insert_after" || edit.op === "insert_before") {
127
- checks.push({ opIndex, which: "anchor", op: edit.op, cited: edit.anchor, status });
128
- }
129
- }
130
- return checks;
143
+ const checks: AnchorCheck[] = [];
144
+ for (let opIndex = 0; opIndex < edits.length; opIndex++) {
145
+ const edit = edits[opIndex];
146
+ if (edit.op === "replace" || edit.op === "delete") {
147
+ checks.push({ opIndex, which: "anchor", op: edit.op, cited: edit.start, status });
148
+ if (edit.end) checks.push({ opIndex, which: "end", op: edit.op, cited: edit.end, status });
149
+ } else if (edit.op === "insert_after" || edit.op === "insert_before") {
150
+ checks.push({ opIndex, which: "anchor", op: edit.op, cited: edit.anchor, status });
151
+ }
152
+ }
153
+ return checks;
131
154
  }
132
155
 
133
156
  /** Translate an Edit into a SpanOp, verifying anchors and ranges against the current lines. */
134
157
  function translateEdit(
135
- edit: Edit,
136
- opIndex: number,
137
- lines: readonly string[],
138
- hashLen: number,
139
- radius: number,
158
+ edit: Edit,
159
+ opIndex: number,
160
+ lines: readonly string[],
161
+ hashLen: number,
162
+ radius: number,
140
163
  ): TranslateResult {
141
- switch (edit.op) {
142
- case "replace":
143
- case "delete": {
144
- const failures: AnchorFailure[] = [];
145
- const checks: AnchorCheck[] = [];
146
- const startF = verifyAnchor(lines, edit.start, "anchor", opIndex, edit.op, hashLen, radius);
147
- checks.push(checkedAnchor(edit, opIndex, "anchor", edit.start, startF));
148
- if (startF) failures.push(startF);
149
- let endLine = edit.start.line;
150
- if (edit.end) {
151
- const endF = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
152
- checks.push(checkedAnchor(edit, opIndex, "end", edit.end, endF));
153
- if (endF) failures.push(endF);
154
- endLine = edit.end.line;
155
- }
156
- if (failures.length > 0) return { ok: false, anchorFailures: failures, checks };
157
- if (endLine < edit.start.line) return { ok: false, rangeError: `range ${edit.start.line}..${endLine} ends before it starts`, checks };
158
- return {
159
- ok: true,
160
- checks,
161
- op: { lo: edit.start.line - 1, hi: endLine, newLines: edit.op === "delete" ? [] : edit.body },
162
- };
163
- }
164
- case "insert_after":
165
- case "insert_before": {
166
- const failure = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
167
- const checks = [checkedAnchor(edit, opIndex, "anchor", edit.anchor, failure)];
168
- if (failure) return { ok: false, anchorFailures: [failure], checks };
169
- const line = edit.anchor.line - (edit.op === "insert_before" ? 1 : 0);
170
- return { ok: true, checks, op: { lo: line, hi: line, newLines: edit.body } };
171
- }
172
- case "append":
173
- return { ok: true, checks: [], op: { lo: lines.length, hi: lines.length, newLines: edit.body } };
174
- case "prepend":
175
- return { ok: true, checks: [], op: { lo: 0, hi: 0, newLines: edit.body } };
176
- }
164
+ switch (edit.op) {
165
+ case "replace":
166
+ case "delete": {
167
+ const failures: AnchorFailure[] = [];
168
+ const checks: AnchorCheck[] = [];
169
+ const startF = verifyAnchor(lines, edit.start, "anchor", opIndex, edit.op, hashLen, radius);
170
+ checks.push(checkedAnchor(edit, opIndex, "anchor", edit.start, startF));
171
+ if (startF) failures.push(startF);
172
+ let endLine = edit.start.line;
173
+ if (edit.end) {
174
+ const endF = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
175
+ checks.push(checkedAnchor(edit, opIndex, "end", edit.end, endF));
176
+ if (endF) failures.push(endF);
177
+ endLine = edit.end.line;
178
+ }
179
+ if (failures.length > 0) return { ok: false, anchorFailures: failures, checks };
180
+ if (endLine < edit.start.line)
181
+ return {
182
+ ok: false,
183
+ rangeError: `range ${edit.start.line}..${endLine} ends before it starts`,
184
+ checks,
185
+ };
186
+ return {
187
+ ok: true,
188
+ checks,
189
+ op: {
190
+ lo: edit.start.line - 1,
191
+ hi: endLine,
192
+ newLines: edit.op === "delete" ? [] : edit.body,
193
+ },
194
+ };
195
+ }
196
+ case "insert_after":
197
+ case "insert_before": {
198
+ const failure = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
199
+ const checks = [checkedAnchor(edit, opIndex, "anchor", edit.anchor, failure)];
200
+ if (failure) return { ok: false, anchorFailures: [failure], checks };
201
+ const line = edit.anchor.line - (edit.op === "insert_before" ? 1 : 0);
202
+ return { ok: true, checks, op: { lo: line, hi: line, newLines: edit.body } };
203
+ }
204
+ case "append":
205
+ return {
206
+ ok: true,
207
+ checks: [],
208
+ op: { lo: lines.length, hi: lines.length, newLines: edit.body },
209
+ };
210
+ case "prepend":
211
+ return { ok: true, checks: [], op: { lo: 0, hi: 0, newLines: edit.body } };
212
+ }
177
213
  }
178
214
 
179
-
180
215
  function hasInvalidBodyLine(edits: readonly Edit[]): boolean {
181
- return edits.some((edit) => "body" in edit && edit.body.some((line) => /[\r\n]/.test(line)));
216
+ return edits.some((edit) => "body" in edit && edit.body.some((line) => /[\r\n]/.test(line)));
182
217
  }
183
218
 
184
219
  /**
@@ -193,104 +228,136 @@ function hasInvalidBodyLine(edits: readonly Edit[]): boolean {
193
228
  * @param hashLen hash length used to verify anchors (default 4)
194
229
  * @param shiftRadius first-pass ±line radius before full-file recovery (default 15; 0 disables recovery)
195
230
  */
196
- export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius = DEFAULT_SHIFT_RADIUS): ApplyResult {
197
- if (hasInvalidBodyLine(edits)) {
198
- return { ok: false, failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line.", checks: inputAnchorChecks(edits, "not_checked") } };
199
- }
200
- const lines = splitLines(text);
201
- const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
202
- const ending = detectLineEnding(text);
231
+ export function applyEdits(
232
+ text: string,
233
+ edits: Edit[],
234
+ hashLen = 4,
235
+ shiftRadius = DEFAULT_SHIFT_RADIUS,
236
+ ): ApplyResult {
237
+ if (hasInvalidBodyLine(edits)) {
238
+ return {
239
+ ok: false,
240
+ failure: {
241
+ kind: "input",
242
+ message: "INVALID_BODY: each body element must contain exactly one logical line.",
243
+ checks: inputAnchorChecks(edits, "not_checked"),
244
+ },
245
+ };
246
+ }
247
+ const lines = splitLines(text);
248
+ const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
249
+ const ending = detectLineEnding(text);
203
250
 
204
- const ops: SpanOp[] = [];
205
- const anchorFailures: AnchorFailure[] = [];
206
- const anchorChecks: AnchorCheck[] = [];
207
- let rangeError: string | null = null;
251
+ const ops: SpanOp[] = [];
252
+ const anchorFailures: AnchorFailure[] = [];
253
+ const anchorChecks: AnchorCheck[] = [];
254
+ let rangeError: string | null = null;
208
255
 
209
- for (let i = 0; i < edits.length; i++) {
210
- const t = translateEdit(edits[i], i, lines, hashLen, shiftRadius);
211
- anchorChecks.push(...t.checks);
212
- if (t.ok) {
213
- ops.push(t.op);
214
- } else if ("anchorFailures" in t) {
215
- anchorFailures.push(...t.anchorFailures);
216
- } else if (rangeError === null) {
217
- rangeError = t.rangeError;
218
- }
219
- }
256
+ for (let i = 0; i < edits.length; i++) {
257
+ const t = translateEdit(edits[i], i, lines, hashLen, shiftRadius);
258
+ anchorChecks.push(...t.checks);
259
+ if (t.ok) {
260
+ ops.push(t.op);
261
+ } else if ("anchorFailures" in t) {
262
+ anchorFailures.push(...t.anchorFailures);
263
+ } else if (rangeError === null) {
264
+ rangeError = t.rangeError;
265
+ }
266
+ }
220
267
 
221
- // Anchor failures take priority: the model must fix anchors first; range
222
- // issues among surviving ops are premature until anchors are corrected.
223
- if (anchorFailures.length > 0) {
224
- return { ok: false, failure: { kind: "anchor", failures: anchorFailures, checks: anchorChecks } };
225
- }
226
- if (rangeError !== null) {
227
- return { ok: false, failure: { kind: "range", message: rangeError, checks: anchorChecks } };
228
- }
268
+ // Anchor failures take priority: the model must fix anchors first; range
269
+ // issues among surviving ops are premature until anchors are corrected.
270
+ if (anchorFailures.length > 0) {
271
+ return {
272
+ ok: false,
273
+ failure: { kind: "anchor", failures: anchorFailures, checks: anchorChecks },
274
+ };
275
+ }
276
+ if (rangeError !== null) {
277
+ return { ok: false, failure: { kind: "range", message: rangeError, checks: anchorChecks } };
278
+ }
229
279
 
230
- const sorted = [...ops].sort((a, b) => a.lo - b.lo || a.hi - b.hi);
231
- const conflict = findSortedRangeConflict(sorted.map((op) => [op.lo, op.hi]));
232
- if (conflict !== undefined) {
233
- return {
234
- ok: false,
235
- failure: {
236
- kind: "range",
237
- message: `overlapping edits near line ${sorted[conflict].lo + 1}; issue one edit per range`,
238
- checks: anchorChecks,
239
- },
240
- };
241
- }
280
+ const sorted = [...ops].sort((a, b) => a.lo - b.lo || a.hi - b.hi);
281
+ const conflict = findSortedRangeConflict(sorted.map((op) => [op.lo, op.hi]));
282
+ if (conflict !== undefined) {
283
+ return {
284
+ ok: false,
285
+ failure: {
286
+ kind: "range",
287
+ message: `overlapping edits near line ${sorted[conflict].lo + 1}; issue one edit per range`,
288
+ checks: anchorChecks,
289
+ },
290
+ };
291
+ }
242
292
 
243
- // Mixed line endings: each line carries the separator that FOLLOWED it in
244
- // the original (its gap), so surviving lines keep theirs byte for byte. New
245
- // gaps borrow the removed block's separators positionally — the last new
246
- // line inherits the block's trailing gap, leaving the boundary to the next
247
- // surviving line unchanged. Internal gaps use the same positional/last-gap
248
- // rule as substring replacements, falling back to the file style for insertions.
249
- const separators = lineSeparators(text);
250
- const separator = ending === "crlf" ? "\r\n" : "\n";
251
- // Verify legacy anchors above before separating the file BOM from movable line content.
252
- let result = lines.map((content, i) => ({ content: bom && i === 0 ? content.slice(1) : content, separator: separators[i] ?? "" }));
253
- for (const op of [...sorted].sort((a, b) => b.lo - a.lo)) {
254
- const removed = result.slice(op.lo, op.hi);
255
- // The trailing gap is outside the logical replacement, just as in substring replacement.
256
- const removedSeparators = removed.slice(0, -1).map((line) => line.separator);
257
- const inserted = op.newLines.map((content, i) => ({
258
- // A copied first-line BOM denotes the existing file header, not a second BOM.
259
- content: bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
260
- separator: i === op.newLines.length - 1 && removed.length > 0
261
- ? removed[removed.length - 1].separator
262
- : replacementSeparator(removedSeparators, i, separator),
263
- }));
264
- result.splice(op.lo, op.hi - op.lo, ...inserted);
265
- }
266
- const finalNewline = hasFinalNewline(text);
267
- const newText = bom + result.map(({ content, separator: current }, i) =>
268
- content + (i < result.length - 1 || finalNewline ? current || separator : ""),
269
- ).join("");
270
- if (newText === text) {
271
- return { ok: true, text, changed: false, touchedLines: [], contextLines: [] };
272
- }
293
+ // Mixed line endings: each line carries the separator that FOLLOWED it in
294
+ // the original (its gap), so surviving lines keep theirs byte for byte. New
295
+ // gaps borrow the removed block's separators positionally — the last new
296
+ // line inherits the block's trailing gap, leaving the boundary to the next
297
+ // surviving line unchanged. Internal gaps use the same positional/last-gap
298
+ // rule as substring replacements, falling back to the file style for insertions.
299
+ const separator = ending === "crlf" ? "\r\n" : "\n";
300
+ // LF-only files have uniform separators; skip the regex scan.
301
+ const separators = ending === "lf" ? undefined : lineSeparators(text);
302
+ // Verify legacy anchors above before separating the file BOM from movable line content.
303
+ let result = lines.map((content, i) => ({
304
+ content: bom && i === 0 ? content.slice(1) : content,
305
+ separator: separators?.[i] ?? "",
306
+ }));
307
+ for (const op of [...sorted].sort((a, b) => b.lo - a.lo)) {
308
+ const removed = result.slice(op.lo, op.hi);
309
+ // The trailing gap is outside the logical replacement, just as in substring replacement.
310
+ const removedSeparators = removed.slice(0, -1).map((line) => line.separator);
311
+ const inserted = op.newLines.map((content, i) => ({
312
+ // A copied first-line BOM denotes the existing file header, not a second BOM.
313
+ content:
314
+ bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
315
+ separator:
316
+ i === op.newLines.length - 1 && removed.length > 0
317
+ ? removed[removed.length - 1].separator
318
+ : replacementSeparator(removedSeparators, i, separator),
319
+ }));
320
+ result.splice(op.lo, op.hi - op.lo, ...inserted);
321
+ }
322
+ const finalNewline = hasFinalNewline(text);
323
+ const newText =
324
+ bom +
325
+ result
326
+ .map(
327
+ ({ content, separator: current }, i) =>
328
+ content + (i < result.length - 1 || finalNewline ? current || separator : ""),
329
+ )
330
+ .join("");
331
+ if (newText === text) {
332
+ return { ok: true, text, changed: false, touchedLines: [], contextLines: [] };
333
+ }
273
334
 
274
- // touchedLines: new-file indices worth re-anchoring — each produced line,
275
- // and for a pure delete the line that shifted into the gap (so the model
276
- // gets a fresh anchor for the shifted region).
277
- const touched: number[] = [];
278
- const contextLines = new Set<number>();
279
- let delta = 0;
280
- for (const op of sorted) {
281
- const newLo = op.lo + delta;
282
- if (op.newLines.length > 0) {
283
- for (let i = 0; i < op.newLines.length; i++) {
284
- touched.push(newLo + i);
285
- // An adjacent replacement may supply the deletion successor itself.
286
- contextLines.delete(newLo + i);
287
- }
288
- } else if (newLo < result.length) {
289
- touched.push(newLo);
290
- contextLines.add(newLo);
291
- }
292
- delta += op.newLines.length - (op.hi - op.lo);
293
- }
335
+ // touchedLines: new-file indices worth re-anchoring — each produced line,
336
+ // and for a pure delete the line that shifted into the gap (so the model
337
+ // gets a fresh anchor for the shifted region).
338
+ const touched: number[] = [];
339
+ const contextLines = new Set<number>();
340
+ let delta = 0;
341
+ for (const op of sorted) {
342
+ const newLo = op.lo + delta;
343
+ if (op.newLines.length > 0) {
344
+ for (let i = 0; i < op.newLines.length; i++) {
345
+ touched.push(newLo + i);
346
+ // An adjacent replacement may supply the deletion successor itself.
347
+ contextLines.delete(newLo + i);
348
+ }
349
+ } else if (op.hi > op.lo && newLo < result.length) {
350
+ touched.push(newLo);
351
+ contextLines.add(newLo);
352
+ }
353
+ delta += op.newLines.length - (op.hi - op.lo);
354
+ }
294
355
 
295
- return { ok: true, text: newText, changed: true, touchedLines: touched, contextLines: [...contextLines] };
356
+ return {
357
+ ok: true,
358
+ text: newText,
359
+ changed: true,
360
+ touchedLines: touched,
361
+ contextLines: [...contextLines],
362
+ };
296
363
  }
@@ -5,54 +5,92 @@ import { computeLineHash, hashFileLines } from "./hash.ts";
5
5
  const ALLOWED = new Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ");
6
6
 
7
7
  test("computeLineHash is stable and base32", () => {
8
- const a = computeLineHash(3, "code", 4);
9
- const b = computeLineHash(3, "code", 4);
10
- assert.equal(a, b);
11
- assert.equal(a.length, 4);
12
- for (const ch of a) assert.ok(ALLOWED.has(ch), `bad char ${ch}`);
8
+ const a = computeLineHash(3, "code", 4);
9
+ const b = computeLineHash(3, "code", 4);
10
+ assert.equal(a, b);
11
+ assert.equal(a.length, 4);
12
+ for (const ch of a) assert.ok(ALLOWED.has(ch), `bad char ${ch}`);
13
13
  });
14
14
 
15
15
  test("different line number → different hash (even for identical content)", () => {
16
- assert.notEqual(computeLineHash(2, ""), computeLineHash(5, ""));
17
- assert.notEqual(computeLineHash(1, "}"), computeLineHash(2, "}"));
16
+ assert.notEqual(computeLineHash(2, ""), computeLineHash(5, ""));
17
+ assert.notEqual(computeLineHash(1, "}"), computeLineHash(2, "}"));
18
18
  });
19
19
 
20
20
  test("different content → different hash", () => {
21
- assert.notEqual(computeLineHash(1, "a"), computeLineHash(1, "b"));
21
+ assert.notEqual(computeLineHash(1, "a"), computeLineHash(1, "b"));
22
22
  });
23
23
 
24
24
  test("same (line, content) → same hash", () => {
25
- assert.equal(computeLineHash(7, "x"), computeLineHash(7, "x"));
25
+ assert.equal(computeLineHash(7, "x"), computeLineHash(7, "x"));
26
26
  });
27
27
 
28
28
  test("base32 alphabet (without I/L/O/U) in bulk", () => {
29
- for (let i = 0; i < 2000; i++) {
30
- const h = computeLineHash(i + 1, `line ${i}`, 4);
31
- for (const ch of h) assert.ok(ALLOWED.has(ch), `bad char ${ch} in ${h}`);
32
- }
29
+ for (let i = 0; i < 2000; i++) {
30
+ const h = computeLineHash(i + 1, `line ${i}`, 4);
31
+ for (const ch of h) assert.ok(ALLOWED.has(ch), `bad char ${ch} in ${h}`);
32
+ }
33
33
  });
34
34
 
35
35
  test("hashFileLines length equals line count", () => {
36
- assert.equal(hashFileLines(["a", "b", "c"]).length, 3);
36
+ assert.equal(hashFileLines(["a", "b", "c"]).length, 3);
37
37
  });
38
38
 
39
39
  test("hashFileLines empty file", () => {
40
- assert.deepEqual(hashFileLines([]), []);
40
+ assert.deepEqual(hashFileLines([]), []);
41
41
  });
42
42
 
43
43
  test("hashFileLines normally disambiguates repeated content without changing hash length", () => {
44
- const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
45
- const hashes = hashFileLines(lines);
46
- assert.equal(new Set(hashes).size, hashes.length, "unexpected collision in fixture");
47
- for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
44
+ const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
45
+ const hashes = hashFileLines(lines);
46
+ assert.equal(new Set(hashes).size, hashes.length, "unexpected collision in fixture");
47
+ for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
48
48
  });
49
49
 
50
50
  test("truncated checksums can collide", () => {
51
- assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
52
- assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
51
+ assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
52
+ assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
53
53
  });
54
54
 
55
55
  test("hashFileLines respects the length parameter", () => {
56
- assert.equal(hashFileLines(["a", "b"], 6)[0].length, 6);
57
- assert.equal(hashFileLines(["a", "b"], 4)[0].length, 4);
56
+ assert.equal(hashFileLines(["a", "b"], 6)[0].length, 6);
57
+ assert.equal(hashFileLines(["a", "b"], 4)[0].length, 4);
58
+ });
59
+
60
+ test("hashLen 8 has a leading zero due to the 32-bit hash limit", () => {
61
+ for (let i = 1; i <= 20; i++) {
62
+ const h = computeLineHash(i, `content ${i}`, 8);
63
+ assert.equal(h.length, 8);
64
+ assert.equal(h[0], "0");
65
+ }
66
+ });
67
+
68
+ test("computeLineHash produces output identical to hashing full interpolated string", () => {
69
+ function referenceHash(line: number, content: string, len = 4): string {
70
+ let h = 0x811c9dc5;
71
+ const str = `${line}\n${content}`;
72
+ for (let i = 0; i < str.length; i++) {
73
+ h ^= str.charCodeAt(i);
74
+ h = Math.imul(h, 0x01000193);
75
+ }
76
+ let s = "";
77
+ const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
78
+ let n = h >>> 0;
79
+ for (let i = 0; i < len; i++) {
80
+ s = BASE32[n & 31] + s;
81
+ n = n >>> 5;
82
+ }
83
+ return s;
84
+ }
85
+ for (const line of [1, 9, 10, 99, 100, 999, 10000]) {
86
+ for (const content of [
87
+ "",
88
+ "a",
89
+ "function test() {}",
90
+ "long line with symbols !@#$%^&*()_+-=[]{}|;:,.<>?/`~",
91
+ ]) {
92
+ assert.equal(computeLineHash(line, content, 4), referenceHash(line, content, 4));
93
+ assert.equal(computeLineHash(line, content, 6), referenceHash(line, content, 6));
94
+ }
95
+ }
58
96
  });