@criogaid/pi-hashline-edit 0.1.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.
- package/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +50 -0
- package/src/core/apply.test.ts +327 -0
- package/src/core/apply.ts +264 -0
- package/src/core/hash.test.ts +54 -0
- package/src/core/hash.ts +68 -0
- package/src/core/index.ts +13 -0
- package/src/core/lines.test.ts +33 -0
- package/src/core/lines.ts +52 -0
- package/src/core/types.ts +87 -0
- package/src/index.ts +44 -0
- package/src/integration/grep-rg.test.ts +390 -0
- package/src/pi/action-fusion.test.ts +244 -0
- package/src/pi/action-fusion.ts +284 -0
- package/src/pi/config.test.ts +22 -0
- package/src/pi/config.ts +56 -0
- package/src/pi/edit-tool.ts +367 -0
- package/src/pi/execute.test.ts +521 -0
- package/src/pi/failure-context.test.ts +88 -0
- package/src/pi/failure-context.ts +98 -0
- package/src/pi/failure-path.test.ts +60 -0
- package/src/pi/file-commit.test.ts +200 -0
- package/src/pi/file-commit.ts +185 -0
- package/src/pi/fusion-card.test.ts +69 -0
- package/src/pi/fusion-card.ts +78 -0
- package/src/pi/grep-tool.ts +795 -0
- package/src/pi/grep.test.ts +515 -0
- package/src/pi/pi.test.ts +19 -0
- package/src/pi/read-tool.ts +178 -0
- package/src/pi/registration.test.ts +41 -0
- package/src/pi/render.ts +103 -0
- package/src/pi/replace-tool.ts +303 -0
- package/src/pi/replace.test.ts +287 -0
- package/src/pi/rg-line-filter.test.ts +79 -0
- package/src/pi/rg-line-filter.ts +358 -0
- package/src/pi/rg-line-ranges.test.ts +30 -0
- package/src/pi/rg-line-ranges.ts +106 -0
- package/src/pi/state.ts +27 -0
- package/src/pi/write-tool.ts +83 -0
- package/src/pi/write.test.ts +126 -0
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { computeLineHash } from "./hash.ts";
|
|
4
|
+
import { splitLines } from "./lines.ts";
|
|
5
|
+
import { applyEdits } from "./apply.ts";
|
|
6
|
+
import type { Anchor } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
/** Live anchor: hash the current content at the given line (1-based). */
|
|
9
|
+
function at(text: string, line: number): Anchor {
|
|
10
|
+
return { line, hash: computeLineHash(line, splitLines(text)[line - 1]) };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// --- happy paths ---
|
|
14
|
+
|
|
15
|
+
test("replace single line", () => {
|
|
16
|
+
const text = "a\nb\nc\n";
|
|
17
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 2), body: ["B"] }]);
|
|
18
|
+
assert.equal(r.ok, true);
|
|
19
|
+
if (r.ok) assert.equal(r.text, "a\nB\nc\n");
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("editing another line preserves standalone carriage returns at EOF", () => {
|
|
23
|
+
for (const ending of ["\n", "\r\n"]) {
|
|
24
|
+
const text = `first${ending}last\r`;
|
|
25
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["changed"] }]);
|
|
26
|
+
assert.equal(r.ok, true);
|
|
27
|
+
if (r.ok) assert.equal(r.text, `changed${ending}last\r`);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("replace range", () => {
|
|
32
|
+
const text = "a\nb\nc\nd\ne\n";
|
|
33
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 2), end: at(text, 4), body: ["X", "Y"] }]);
|
|
34
|
+
assert.equal(r.ok, true);
|
|
35
|
+
if (r.ok) assert.equal(r.text, "a\nX\nY\ne\n");
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("delete single line / range", () => {
|
|
39
|
+
const text = "a\nb\nc\nd\n";
|
|
40
|
+
const r = applyEdits(text, [{ op: "delete", start: at(text, 2), end: at(text, 3) }]);
|
|
41
|
+
assert.equal(r.ok, true);
|
|
42
|
+
if (r.ok) assert.equal(r.text, "a\nd\n");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("insert_after", () => {
|
|
46
|
+
const text = "a\nb\n";
|
|
47
|
+
const r = applyEdits(text, [{ op: "insert_after", anchor: at(text, 1), body: ["x"] }]);
|
|
48
|
+
assert.equal(r.ok, true);
|
|
49
|
+
if (r.ok) assert.equal(r.text, "a\nx\nb\n");
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("insert_before", () => {
|
|
53
|
+
const text = "a\nb\n";
|
|
54
|
+
const r = applyEdits(text, [{ op: "insert_before", anchor: at(text, 2), body: ["x"] }]);
|
|
55
|
+
assert.equal(r.ok, true);
|
|
56
|
+
if (r.ok) assert.equal(r.text, "a\nx\nb\n");
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("append / prepend", () => {
|
|
60
|
+
const text = "a\nb\n";
|
|
61
|
+
const r = applyEdits(text, [
|
|
62
|
+
{ op: "prepend", body: ["head"] },
|
|
63
|
+
{ op: "append", body: ["tail"] },
|
|
64
|
+
]);
|
|
65
|
+
assert.equal(r.ok, true);
|
|
66
|
+
if (r.ok) assert.equal(r.text, "head\na\nb\ntail\n");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("multiple out-of-order ops → applied at the right positions", () => {
|
|
70
|
+
const text = "a\nb\nc\n";
|
|
71
|
+
const r = applyEdits(text, [
|
|
72
|
+
{ op: "insert_after", anchor: at(text, 3), body: ["z"] },
|
|
73
|
+
{ op: "replace", start: at(text, 1), body: ["A"] },
|
|
74
|
+
]);
|
|
75
|
+
assert.equal(r.ok, true);
|
|
76
|
+
if (r.ok) assert.equal(r.text, "A\nb\nc\nz\n");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("touchedLines covers exactly the lines this edit produced (new-file indices)", () => {
|
|
80
|
+
const text = "a\nb\nc\n";
|
|
81
|
+
const r = applyEdits(text, [
|
|
82
|
+
{ op: "insert_after", anchor: at(text, 3), body: ["z"] },
|
|
83
|
+
{ op: "replace", start: at(text, 1), body: ["A"] },
|
|
84
|
+
]);
|
|
85
|
+
assert.equal(r.ok, true);
|
|
86
|
+
if (r.ok) {
|
|
87
|
+
// new file: [A, b, c, z]; this edit produced line index 0 (A) and 3 (z)
|
|
88
|
+
assert.deepEqual([...r.touchedLines], [0, 3]);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("touchedLines for append", () => {
|
|
93
|
+
const text = "a\n";
|
|
94
|
+
const r = applyEdits(text, [{ op: "append", body: ["b", "c"] }]);
|
|
95
|
+
assert.equal(r.ok, true);
|
|
96
|
+
if (r.ok) assert.deepEqual([...r.touchedLines], [1, 2]);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("touchedLines for delete re-anchors the line that shifted into the gap", () => {
|
|
100
|
+
const text = "a\nb\nc\nd\n";
|
|
101
|
+
const r = applyEdits(text, [{ op: "delete", start: at(text, 2) }]);
|
|
102
|
+
assert.equal(r.ok, true);
|
|
103
|
+
if (r.ok) {
|
|
104
|
+
// new file: [a, c, d]; deleting line 2 (b) shifts c into index 1
|
|
105
|
+
assert.deepEqual([...r.touchedLines], [1]);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// --- error paths ---
|
|
110
|
+
|
|
111
|
+
test("anchor hash mismatch rejected (line changed)", () => {
|
|
112
|
+
const text = "a\nb\n";
|
|
113
|
+
const r = applyEdits(text, [{ op: "replace", start: { line: 1, hash: "WRONG" }, body: ["x"] }]);
|
|
114
|
+
assert.equal(r.ok, false);
|
|
115
|
+
if (!r.ok) assert.equal(r.failure.kind, "anchor");
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("line out of range rejected", () => {
|
|
119
|
+
const text = "a\n";
|
|
120
|
+
const r = applyEdits(text, [{ op: "replace", start: { line: 5, hash: computeLineHash(1, "a") }, body: ["x"] }]);
|
|
121
|
+
assert.equal(r.ok, false);
|
|
122
|
+
if (!r.ok) assert.equal(r.failure.kind, "anchor");
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("anchor mismatch when the cited line's content differs (live verification)", () => {
|
|
126
|
+
// hash for line 2's content, but cited as line 1 → must fail because line 1's live content differs
|
|
127
|
+
const text = "a\nb\n";
|
|
128
|
+
const r = applyEdits(text, [{ op: "replace", start: { line: 1, hash: computeLineHash(2, "b") }, body: ["x"] }]);
|
|
129
|
+
assert.equal(r.ok, false);
|
|
130
|
+
if (!r.ok) assert.equal(r.failure.kind, "anchor");
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("reverse-order range rejected", () => {
|
|
134
|
+
const text = "a\nb\nc\n";
|
|
135
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 3), end: at(text, 1), body: ["x"] }]);
|
|
136
|
+
assert.equal(r.ok, false);
|
|
137
|
+
if (!r.ok) assert.equal(r.failure.kind, "range");
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("overlapping edits rejected", () => {
|
|
141
|
+
const text = "a\nb\nc\nd\n";
|
|
142
|
+
const r = applyEdits(text, [
|
|
143
|
+
{ op: "replace", start: at(text, 2), end: at(text, 3), body: ["x"] },
|
|
144
|
+
{ op: "replace", start: at(text, 3), body: ["y"] },
|
|
145
|
+
]);
|
|
146
|
+
assert.equal(r.ok, false);
|
|
147
|
+
if (!r.ok) assert.equal(r.failure.kind, "range");
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("conflict at the same insertion point rejected", () => {
|
|
151
|
+
const text = "a\nb\n";
|
|
152
|
+
const r = applyEdits(text, [
|
|
153
|
+
{ op: "insert_after", anchor: at(text, 1), body: ["x"] },
|
|
154
|
+
{ op: "insert_after", anchor: at(text, 1), body: ["y"] },
|
|
155
|
+
]);
|
|
156
|
+
assert.equal(r.ok, false);
|
|
157
|
+
if (!r.ok) assert.equal(r.failure.kind, "range");
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("noop (byte-identical body) rejected", () => {
|
|
161
|
+
const text = "a\nb\n";
|
|
162
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["a"] }]);
|
|
163
|
+
assert.equal(r.ok, false);
|
|
164
|
+
if (!r.ok) assert.equal(r.failure.kind, "noop");
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("unrelated change elsewhere does NOT block the edit (no global stale check)", () => {
|
|
168
|
+
// read-time text and current text differ at line 3, but we only touch line 1 — must succeed
|
|
169
|
+
const readText = "a\nb\nc\n";
|
|
170
|
+
const currentText = "a\nb\nCHANGED\n";
|
|
171
|
+
const r = applyEdits(currentText, [{ op: "replace", start: at(readText, 1), body: ["A"] }]);
|
|
172
|
+
assert.equal(r.ok, true);
|
|
173
|
+
if (r.ok) assert.equal(r.text, "A\nb\nCHANGED\n");
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("CRLF line endings preserved", () => {
|
|
177
|
+
const text = "a\r\nb\r\n";
|
|
178
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["A"] }]);
|
|
179
|
+
assert.equal(r.ok, true);
|
|
180
|
+
if (r.ok) assert.equal(r.text, "A\r\nb\r\n");
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test("editing a mixed-ending file preserves untouched separators", () => {
|
|
184
|
+
const before = "first\r\nsecond\nthird\r\n";
|
|
185
|
+
const result = applyEdits(before, [{ op: "replace", start: at(before, 2), body: ["SECOND"] }]);
|
|
186
|
+
assert.equal(result.ok, true);
|
|
187
|
+
if (result.ok) assert.equal(result.text, "first\r\nSECOND\nthird\r\n");
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test("inserting and deleting in mixed-ending files preserves surviving separators", () => {
|
|
191
|
+
const before = "a\r\nb\nc\r\nlast";
|
|
192
|
+
const inserted = applyEdits(before, [{ op: "insert_after", anchor: at(before, 2), body: ["x"] }]);
|
|
193
|
+
assert.equal(inserted.ok, true);
|
|
194
|
+
if (inserted.ok) assert.equal(inserted.text, "a\r\nb\nx\r\nc\r\nlast");
|
|
195
|
+
const deleted = applyEdits(before, [{ op: "delete", start: at(before, 2) }]);
|
|
196
|
+
assert.equal(deleted.ok, true);
|
|
197
|
+
if (deleted.ok) assert.equal(deleted.text, "a\r\nc\r\nlast");
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("replacing one line with several keeps the block's trailing gap", () => {
|
|
201
|
+
const before = "a\r\nb\nc\r\nd";
|
|
202
|
+
const result = applyEdits(before, [{ op: "replace", start: at(before, 2), body: ["X", "Y", "Z"] }]);
|
|
203
|
+
assert.equal(result.ok, true);
|
|
204
|
+
// b's gap (\n) moves to the last new line, so the boundary to c is unchanged;
|
|
205
|
+
// the two new interior gaps borrow positionally, then fall back to crlf.
|
|
206
|
+
if (result.ok) assert.equal(result.text, "a\r\nX\nY\r\nZ\nc\r\nd");
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("a file without a final newline keeps not having one", () => {
|
|
210
|
+
const text = "a\nb";
|
|
211
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 2), body: ["B"] }]);
|
|
212
|
+
assert.equal(r.ok, true);
|
|
213
|
+
if (r.ok) assert.equal(r.text, "a\nB");
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("CRLF without a final newline keeps not having one", () => {
|
|
217
|
+
const text = "a\r\nb";
|
|
218
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["A"] }]);
|
|
219
|
+
assert.equal(r.ok, true);
|
|
220
|
+
if (r.ok) assert.equal(r.text, "A\r\nb");
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("appending to a file without a final newline keeps it absent", () => {
|
|
224
|
+
const text = "a";
|
|
225
|
+
const r = applyEdits(text, [{ op: "append", body: ["b"] }]);
|
|
226
|
+
assert.equal(r.ok, true);
|
|
227
|
+
if (r.ok) assert.equal(r.text, "a\nb");
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
test("noop is still detected when the file lacks a final newline", () => {
|
|
231
|
+
const text = "a\nb";
|
|
232
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["a"] }]);
|
|
233
|
+
assert.equal(r.ok, false);
|
|
234
|
+
if (!r.ok) assert.equal(r.failure.kind, "noop");
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// --- shifted-anchor recovery ---
|
|
238
|
+
|
|
239
|
+
test("shifted recovery: content moved down → found with a fresh anchor", () => {
|
|
240
|
+
const readText = "a\nb\nc\nd\ne\n";
|
|
241
|
+
const currentText = "a\nX\nb\nc\nd\ne\n"; // inserted X after line 1 → "c" moved 3→4
|
|
242
|
+
const r = applyEdits(currentText, [{ op: "replace", start: at(readText, 3), body: ["C"] }]);
|
|
243
|
+
assert.equal(r.ok, false);
|
|
244
|
+
if (!r.ok && r.failure.kind === "anchor") {
|
|
245
|
+
const f = r.failure.failures[0];
|
|
246
|
+
assert.equal(f.recovery.kind, "found");
|
|
247
|
+
if (f.recovery.kind === "found") {
|
|
248
|
+
assert.equal(f.recovery.newLine, 4);
|
|
249
|
+
// the rescued anchor must verify against the current file
|
|
250
|
+
assert.equal(computeLineHash(4, splitLines(currentText)[3]), f.recovery.newHash);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test("rescued anchor lets the retry succeed without a re-read", () => {
|
|
256
|
+
const readText = "a\nb\nc\nd\ne\n";
|
|
257
|
+
const currentText = "a\nX\nb\nc\nd\ne\n";
|
|
258
|
+
// first attempt with a stale anchor → rescued
|
|
259
|
+
const r1 = applyEdits(currentText, [{ op: "replace", start: at(readText, 3), body: ["C"] }]);
|
|
260
|
+
assert.equal(r1.ok, false);
|
|
261
|
+
if (r1.ok) return;
|
|
262
|
+
if (r1.failure.kind !== "anchor") return;
|
|
263
|
+
const f = r1.failure.failures[0];
|
|
264
|
+
assert.equal(f.recovery.kind, "found");
|
|
265
|
+
if (f.recovery.kind !== "found") return;
|
|
266
|
+
// retry with the rescued anchor → succeeds, file unchanged elsewhere
|
|
267
|
+
const r2 = applyEdits(currentText, [
|
|
268
|
+
{ op: "replace", start: { line: f.recovery.newLine, hash: f.recovery.newHash }, body: ["C"] },
|
|
269
|
+
]);
|
|
270
|
+
assert.equal(r2.ok, true);
|
|
271
|
+
if (r2.ok) assert.equal(r2.text, "a\nX\nb\nC\nd\ne\n");
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
test("shifted recovery: duplicate content → ambiguous candidates", () => {
|
|
275
|
+
const readText = "a\nx\nb\nx\nc\n";
|
|
276
|
+
const currentText = "a\nY\nx\nb\nx\nc\n"; // both "x" shifted
|
|
277
|
+
const r = applyEdits(currentText, [{ op: "replace", start: at(readText, 2), body: ["Z"] }]);
|
|
278
|
+
assert.equal(r.ok, false);
|
|
279
|
+
if (!r.ok && r.failure.kind === "anchor") {
|
|
280
|
+
const f = r.failure.failures[0];
|
|
281
|
+
assert.equal(f.recovery.kind, "ambiguous");
|
|
282
|
+
if (f.recovery.kind === "ambiguous") {
|
|
283
|
+
assert.deepEqual(
|
|
284
|
+
f.recovery.candidates.map((c) => c.line),
|
|
285
|
+
[3, 5],
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
test("shifted recovery: content genuinely changed → none, with live content", () => {
|
|
292
|
+
const readText = "a\nb\nc\n";
|
|
293
|
+
const currentText = "a\nBCHANGED\nc\n"; // "b" is gone
|
|
294
|
+
const r = applyEdits(currentText, [{ op: "replace", start: at(readText, 2), body: ["B"] }]);
|
|
295
|
+
assert.equal(r.ok, false);
|
|
296
|
+
if (!r.ok && r.failure.kind === "anchor") {
|
|
297
|
+
const f = r.failure.failures[0];
|
|
298
|
+
assert.equal(f.recovery.kind, "none");
|
|
299
|
+
assert.equal(f.current?.content, "BCHANGED");
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
test("collect-all: two stale anchors in one batch → both failures returned", () => {
|
|
304
|
+
const readText = "a\nb\nc\nd\n";
|
|
305
|
+
const currentText = "X\na\nb\nc\nd\n"; // inserted X at top → all shifted +1
|
|
306
|
+
const r = applyEdits(currentText, [
|
|
307
|
+
{ op: "replace", start: at(readText, 2), body: ["B"] },
|
|
308
|
+
{ op: "replace", start: at(readText, 4), body: ["D"] },
|
|
309
|
+
]);
|
|
310
|
+
assert.equal(r.ok, false);
|
|
311
|
+
if (!r.ok && r.failure.kind === "anchor") {
|
|
312
|
+
assert.equal(r.failure.failures.length, 2);
|
|
313
|
+
const found = r.failure.failures.map((f) => (f.recovery.kind === "found" ? f.recovery.newLine : -1));
|
|
314
|
+
assert.deepEqual(found, [3, 5]);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
test("shiftRadius=0 disables rescue (always none)", () => {
|
|
319
|
+
const readText = "a\nb\nc\nd\ne\n";
|
|
320
|
+
const currentText = "a\nX\nb\nc\nd\ne\n";
|
|
321
|
+
const r = applyEdits(currentText, [{ op: "replace", start: at(readText, 3), body: ["C"] }], 4, 0);
|
|
322
|
+
assert.equal(r.ok, false);
|
|
323
|
+
if (!r.ok && r.failure.kind === "anchor") {
|
|
324
|
+
assert.equal(r.failure.failures[0].recovery.kind, "none");
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure-function applicator: applies edits to a file's current text.
|
|
3
|
+
*
|
|
4
|
+
* Verification is live and surgical: each anchor's hash is recomputed from the
|
|
5
|
+
* CURRENT line content at the cited line number and compared to the cited hash.
|
|
6
|
+
* No snapshot, no global stale check — a line that changed (or was
|
|
7
|
+
* misremembered) fails its own anchor; unchanged lines elsewhere never block
|
|
8
|
+
* the edit.
|
|
9
|
+
*
|
|
10
|
+
* Shifted-anchor recovery: when a cited anchor no longer matches, we rescan
|
|
11
|
+
* ±radius lines for the original content, holding the ORIGINAL line number fixed
|
|
12
|
+
* and re-hashing each candidate's content. On a unique hit the new anchor (with
|
|
13
|
+
* its freshly computed hash) is returned so the caller can retry without a
|
|
14
|
+
* re-read; on several hits they are reported as ambiguous; on none the live
|
|
15
|
+
* content at the cited line is returned to steer a re-read.
|
|
16
|
+
*
|
|
17
|
+
* Batch semantics: all ops are verified against the same current snapshot. If
|
|
18
|
+
* ANY anchor fails, EVERY failure (with recovery) is collected and returned
|
|
19
|
+
* together — nothing is written. This keeps the rescue report and the on-disk
|
|
20
|
+
* file in sync: a partial write would shift lines and invalidate the very
|
|
21
|
+
* recovery info we just returned. Range issues among the surviving ops are
|
|
22
|
+
* deferred until anchors are corrected.
|
|
23
|
+
*
|
|
24
|
+
* Other strict semantics:
|
|
25
|
+
* - Operation ranges must not overlap (including the same insertion point).
|
|
26
|
+
* - body byte-identical to the whole-file result → `noop` error (guides the
|
|
27
|
+
* model to investigate rather than blindly retry).
|
|
28
|
+
*
|
|
29
|
+
* @module pi-hashline-edit/core
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { computeLineHash } from "./hash.ts";
|
|
33
|
+
import { detectLineEnding, hasFinalNewline, splitLines } from "./lines.ts";
|
|
34
|
+
import type { Anchor, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
|
|
35
|
+
|
|
36
|
+
/** Line-level operation: replace the raw lines in the `[lo, hi)` range (0-based, hi exclusive) with newLines. */
|
|
37
|
+
interface SpanOp {
|
|
38
|
+
lo: number;
|
|
39
|
+
hi: number;
|
|
40
|
+
newLines: string[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Default ±line radius for shifted-anchor recovery. */
|
|
44
|
+
const DEFAULT_SHIFT_RADIUS = 15;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Verify an anchor against the live content; on mismatch, attempt shifted
|
|
48
|
+
* recovery. Returns null when the anchor matches, otherwise an
|
|
49
|
+
* {@link AnchorFailure} carrying the recovery outcome and the cited line's
|
|
50
|
+
* current snapshot.
|
|
51
|
+
*
|
|
52
|
+
* Recovery holds the ORIGINAL line number fixed and re-hashes each candidate's
|
|
53
|
+
* content: `computeLineHash(citedLine, candidateContent) === citedHash` holds
|
|
54
|
+
* iff the candidate IS the original content (modulo negligible hash collision).
|
|
55
|
+
* A returned candidate's anchor uses the candidate's real line number with a
|
|
56
|
+
* hash computed for that line, so it verifies on retry.
|
|
57
|
+
*/
|
|
58
|
+
function verifyAnchor(
|
|
59
|
+
lines: readonly string[],
|
|
60
|
+
cited: Anchor,
|
|
61
|
+
which: "anchor" | "end",
|
|
62
|
+
opIndex: number,
|
|
63
|
+
op: Edit["op"],
|
|
64
|
+
hashLen: number,
|
|
65
|
+
radius: number,
|
|
66
|
+
): AnchorFailure | null {
|
|
67
|
+
const { line, hash } = cited;
|
|
68
|
+
if (line >= 1 && line <= lines.length && computeLineHash(line, lines[line - 1], hashLen) === hash) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Shifted recovery: scan ±radius (excluding the already-failed cited line).
|
|
73
|
+
const candidates: { line: number; hash: string }[] = [];
|
|
74
|
+
const lo = Math.max(1, line - radius);
|
|
75
|
+
const hi = Math.min(lines.length, line + radius);
|
|
76
|
+
for (let c = lo; c <= hi; c++) {
|
|
77
|
+
if (c === line) continue;
|
|
78
|
+
if (computeLineHash(line, lines[c - 1], hashLen) === hash) {
|
|
79
|
+
candidates.push({ line: c, hash: computeLineHash(c, lines[c - 1], hashLen) });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let recovery: AnchorRecovery;
|
|
84
|
+
if (candidates.length === 1) {
|
|
85
|
+
recovery = { kind: "found", newLine: candidates[0].line, newHash: candidates[0].hash };
|
|
86
|
+
} else if (candidates.length > 1) {
|
|
87
|
+
recovery = { kind: "ambiguous", candidates };
|
|
88
|
+
} else {
|
|
89
|
+
recovery = { kind: "none" };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const current =
|
|
93
|
+
line >= 1 && line <= lines.length
|
|
94
|
+
? { hash: computeLineHash(line, lines[line - 1], hashLen), content: lines[line - 1] }
|
|
95
|
+
: null;
|
|
96
|
+
|
|
97
|
+
return { opIndex, which, op, cited, recovery, current };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
type TranslateResult =
|
|
101
|
+
| { readonly ok: true; readonly op: SpanOp }
|
|
102
|
+
| { readonly ok: false; readonly anchorFailures: AnchorFailure[] }
|
|
103
|
+
| { readonly ok: false; readonly rangeError: string };
|
|
104
|
+
|
|
105
|
+
/** Translate an Edit into a SpanOp, verifying anchors and ranges against the current lines. */
|
|
106
|
+
function translateEdit(
|
|
107
|
+
edit: Edit,
|
|
108
|
+
opIndex: number,
|
|
109
|
+
lines: readonly string[],
|
|
110
|
+
hashLen: number,
|
|
111
|
+
radius: number,
|
|
112
|
+
): TranslateResult {
|
|
113
|
+
switch (edit.op) {
|
|
114
|
+
case "replace":
|
|
115
|
+
case "delete": {
|
|
116
|
+
const failures: AnchorFailure[] = [];
|
|
117
|
+
const startF = verifyAnchor(lines, edit.start, "anchor", opIndex, edit.op, hashLen, radius);
|
|
118
|
+
if (startF) failures.push(startF);
|
|
119
|
+
let endLine = edit.start.line;
|
|
120
|
+
if (edit.end) {
|
|
121
|
+
const endF = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
|
|
122
|
+
if (endF) failures.push(endF);
|
|
123
|
+
endLine = edit.end.line;
|
|
124
|
+
}
|
|
125
|
+
if (failures.length > 0) return { ok: false, anchorFailures: failures };
|
|
126
|
+
if (endLine < edit.start.line) {
|
|
127
|
+
return { ok: false, rangeError: `range ${edit.start.line}..${endLine} ends before it starts` };
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
ok: true,
|
|
131
|
+
op: {
|
|
132
|
+
lo: edit.start.line - 1,
|
|
133
|
+
hi: endLine,
|
|
134
|
+
newLines: edit.op === "delete" ? [] : edit.body,
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
case "insert_after": {
|
|
139
|
+
const f = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
|
|
140
|
+
if (f) return { ok: false, anchorFailures: [f] };
|
|
141
|
+
return { ok: true, op: { lo: edit.anchor.line, hi: edit.anchor.line, newLines: edit.body } };
|
|
142
|
+
}
|
|
143
|
+
case "insert_before": {
|
|
144
|
+
const f = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
|
|
145
|
+
if (f) return { ok: false, anchorFailures: [f] };
|
|
146
|
+
return { ok: true, op: { lo: edit.anchor.line - 1, hi: edit.anchor.line - 1, newLines: edit.body } };
|
|
147
|
+
}
|
|
148
|
+
case "append": {
|
|
149
|
+
return { ok: true, op: { lo: lines.length, hi: lines.length, newLines: edit.body } };
|
|
150
|
+
}
|
|
151
|
+
case "prepend": {
|
|
152
|
+
return { ok: true, op: { lo: 0, hi: 0, newLines: edit.body } };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The "last affected position" of a zero-width range (insertion point) is lo; otherwise hi-1. */
|
|
158
|
+
function maxAffected(op: SpanOp): number {
|
|
159
|
+
return op.lo === op.hi ? op.lo : op.hi - 1;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Apply edits to `text`. Anchors are verified against the current content; on
|
|
164
|
+
* success `touchedLines` gives the 0-based indices of the new-file lines this
|
|
165
|
+
* edit produced. On any anchor mismatch, all failures (with shifted recovery)
|
|
166
|
+
* are collected and returned together — nothing is written.
|
|
167
|
+
*
|
|
168
|
+
* @param text current full file text
|
|
169
|
+
* @param edits parsed edit operations
|
|
170
|
+
* @param hashLen hash length used to verify anchors (default 4)
|
|
171
|
+
* @param shiftRadius ±line radius for shifted-anchor recovery (default 15; 0 disables rescue)
|
|
172
|
+
*/
|
|
173
|
+
export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius = DEFAULT_SHIFT_RADIUS): ApplyResult {
|
|
174
|
+
const lines = splitLines(text);
|
|
175
|
+
const ending = detectLineEnding(text);
|
|
176
|
+
|
|
177
|
+
const ops: SpanOp[] = [];
|
|
178
|
+
const anchorFailures: AnchorFailure[] = [];
|
|
179
|
+
let rangeError: string | null = null;
|
|
180
|
+
|
|
181
|
+
for (let i = 0; i < edits.length; i++) {
|
|
182
|
+
const t = translateEdit(edits[i], i, lines, hashLen, shiftRadius);
|
|
183
|
+
if (t.ok) {
|
|
184
|
+
ops.push(t.op);
|
|
185
|
+
} else if ("anchorFailures" in t) {
|
|
186
|
+
anchorFailures.push(...t.anchorFailures);
|
|
187
|
+
} else if (rangeError === null) {
|
|
188
|
+
rangeError = t.rangeError;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Anchor failures take priority: the model must fix anchors first; range
|
|
193
|
+
// issues among surviving ops are premature until anchors are corrected.
|
|
194
|
+
if (anchorFailures.length > 0) {
|
|
195
|
+
return { ok: false, failure: { kind: "anchor", failures: anchorFailures } };
|
|
196
|
+
}
|
|
197
|
+
if (rangeError !== null) {
|
|
198
|
+
return { ok: false, failure: { kind: "range", message: rangeError } };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Overlap check: sort ascending by lo; the next op's start must not fall inside the previous op's affected range
|
|
202
|
+
const sorted = [...ops].sort((a, b) => a.lo - b.lo || a.hi - b.hi);
|
|
203
|
+
for (let k = 1; k < sorted.length; k++) {
|
|
204
|
+
if (sorted[k].lo <= maxAffected(sorted[k - 1])) {
|
|
205
|
+
return {
|
|
206
|
+
ok: false,
|
|
207
|
+
failure: {
|
|
208
|
+
kind: "range",
|
|
209
|
+
message: `overlapping edits near line ${sorted[k].lo + 1}; issue one edit per range`,
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Mixed line endings: each line carries the separator that FOLLOWED it in
|
|
216
|
+
// the original (its gap), so surviving lines keep theirs byte for byte. New
|
|
217
|
+
// gaps borrow the removed block's separators positionally — the last new
|
|
218
|
+
// line inherits the block's trailing gap, leaving the boundary to the next
|
|
219
|
+
// surviving line unchanged; gaps past the removed block's length (or in a
|
|
220
|
+
// pure insertion) fall back to the file's customary ending.
|
|
221
|
+
const separators = text.match(/\r?\n/g) ?? [];
|
|
222
|
+
const separator = ending === "crlf" ? "\r\n" : "\n";
|
|
223
|
+
let result = lines.map((content, i) => ({ content, separator: separators[i] ?? "" }));
|
|
224
|
+
for (const op of [...sorted].sort((a, b) => b.lo - a.lo)) {
|
|
225
|
+
const removed = result.slice(op.lo, op.hi);
|
|
226
|
+
const inserted = op.newLines.map((content, i) => ({
|
|
227
|
+
content,
|
|
228
|
+
separator: i === op.newLines.length - 1 && removed.length > 0
|
|
229
|
+
? removed[removed.length - 1].separator
|
|
230
|
+
: removed[i]?.separator || separator,
|
|
231
|
+
}));
|
|
232
|
+
result.splice(op.lo, op.hi - op.lo, ...inserted);
|
|
233
|
+
}
|
|
234
|
+
const finalNewline = hasFinalNewline(text);
|
|
235
|
+
const newText = result.map(({ content, separator: current }, i) =>
|
|
236
|
+
content + (i < result.length - 1 || finalNewline ? current || separator : ""),
|
|
237
|
+
).join("");
|
|
238
|
+
if (newText === text) {
|
|
239
|
+
return {
|
|
240
|
+
ok: false,
|
|
241
|
+
failure: {
|
|
242
|
+
kind: "noop",
|
|
243
|
+
message: "edit parsed and applied cleanly but produced no change; body is byte-identical — the bug is elsewhere, re-read first",
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// touchedLines: new-file indices worth re-anchoring — each produced line,
|
|
249
|
+
// and for a pure delete the line that shifted into the gap (so the model
|
|
250
|
+
// gets a fresh anchor for the shifted region).
|
|
251
|
+
const touched: number[] = [];
|
|
252
|
+
let delta = 0;
|
|
253
|
+
for (const op of sorted) {
|
|
254
|
+
const newLo = op.lo + delta;
|
|
255
|
+
if (op.newLines.length > 0) {
|
|
256
|
+
for (let i = 0; i < op.newLines.length; i++) touched.push(newLo + i);
|
|
257
|
+
} else if (newLo < result.length) {
|
|
258
|
+
touched.push(newLo);
|
|
259
|
+
}
|
|
260
|
+
delta += op.newLines.length - (op.hi - op.lo);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return { ok: true, text: newText, changed: true, touchedLines: touched };
|
|
264
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { computeLineHash, hashFileLines } from "./hash.ts";
|
|
4
|
+
|
|
5
|
+
const ALLOWED = new Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ");
|
|
6
|
+
|
|
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}`);
|
|
13
|
+
});
|
|
14
|
+
|
|
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, "}"));
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("different content → different hash", () => {
|
|
21
|
+
assert.notEqual(computeLineHash(1, "a"), computeLineHash(1, "b"));
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("same (line, content) → same hash", () => {
|
|
25
|
+
assert.equal(computeLineHash(7, "x"), computeLineHash(7, "x"));
|
|
26
|
+
});
|
|
27
|
+
|
|
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
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("hashFileLines length equals line count", () => {
|
|
36
|
+
assert.equal(hashFileLines(["a", "b", "c"]).length, 3);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("hashFileLines empty file", () => {
|
|
40
|
+
assert.deepEqual(hashFileLines([]), []);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("hashFileLines: identical content lines get distinct hashes (no collision, no length bloat)", () => {
|
|
44
|
+
// runs of identical lines — the case neighbor-aware hashing explodes on
|
|
45
|
+
const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
|
|
46
|
+
const hashes = hashFileLines(lines);
|
|
47
|
+
assert.equal(new Set(hashes).size, hashes.length, "duplicate hashes");
|
|
48
|
+
for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("hashFileLines respects the length parameter", () => {
|
|
52
|
+
assert.equal(hashFileLines(["a", "b"], 6)[0].length, 6);
|
|
53
|
+
assert.equal(hashFileLines(["a", "b"], 4)[0].length, 4);
|
|
54
|
+
});
|