@criogaid/pi-hashline-edit 0.1.3 → 0.3.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/README.md +77 -23
- package/package.json +1 -1
- package/src/core/apply.test.ts +87 -10
- package/src/core/apply.ts +106 -84
- package/src/core/lines.test.ts +12 -1
- package/src/core/lines.ts +43 -1
- package/src/core/ranges.test.ts +28 -0
- package/src/core/ranges.ts +25 -0
- package/src/core/text.ts +5 -0
- package/src/core/types.ts +37 -20
- package/src/integration/grep-rg.test.ts +188 -1
- package/src/pi/action-fusion.test.ts +3 -1
- package/src/pi/action-fusion.ts +38 -35
- package/src/pi/anchor-format.test.ts +30 -0
- package/src/pi/anchor-format.ts +28 -0
- package/src/pi/config.ts +1 -1
- package/src/pi/edit-tool.ts +91 -100
- package/src/pi/execute.test.ts +239 -14
- package/src/pi/failure-context.test.ts +99 -62
- package/src/pi/failure-context.ts +67 -64
- package/src/pi/failure-path.test.ts +20 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/fusion-card.test.ts +38 -1
- package/src/pi/fusion-card.ts +41 -17
- package/src/pi/grep-tool.ts +84 -55
- package/src/pi/grep.test.ts +77 -6
- package/src/pi/mutation-result.ts +48 -9
- package/src/pi/path.ts +22 -0
- package/src/pi/pi.test.ts +64 -2
- package/src/pi/read-tool.ts +9 -30
- package/src/pi/registration.test.ts +28 -1
- package/src/pi/render.test.ts +111 -0
- package/src/pi/render.ts +30 -6
- package/src/pi/replace-tool.ts +144 -140
- package/src/pi/replace.test.ts +193 -1
- package/src/pi/result-safety.test.ts +241 -8
- package/src/pi/rg-line-filter.test.ts +7 -1
- package/src/pi/rg-line-filter.ts +10 -12
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/rg-text-view.ts +88 -0
- package/src/pi/write-tool.ts +13 -47
- package/src/pi/write.test.ts +25 -36
package/src/core/apply.ts
CHANGED
|
@@ -7,12 +7,11 @@
|
|
|
7
7
|
* misremembered) fails its own anchor; unchanged lines elsewhere never block
|
|
8
8
|
* the edit.
|
|
9
9
|
*
|
|
10
|
-
* Shifted-anchor recovery:
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* content at the cited line is returned to steer a re-read.
|
|
10
|
+
* Shifted-anchor recovery: on mismatch, scan ±radius first, then the rest of the
|
|
11
|
+
* file only if no nearby candidates match. Hold the ORIGINAL line number fixed
|
|
12
|
+
* when hashing candidate content; matches are candidates, not proof of identity.
|
|
13
|
+
* Return anchors hashed at their real positions for the caller to inspect and
|
|
14
|
+
* retry. Several hits are ambiguous; radius 0 disables recovery.
|
|
16
15
|
*
|
|
17
16
|
* Batch semantics: all ops are verified against the same current snapshot. If
|
|
18
17
|
* ANY anchor fails, EVERY failure (with recovery) is collected and returned
|
|
@@ -23,15 +22,15 @@
|
|
|
23
22
|
*
|
|
24
23
|
* Other strict semantics:
|
|
25
24
|
* - Operation ranges must not overlap (including the same insertion point).
|
|
26
|
-
* -
|
|
27
|
-
* model to investigate rather than blindly retry).
|
|
25
|
+
* - Byte-identical output succeeds with changed=false and no updated anchors.
|
|
28
26
|
*
|
|
29
27
|
* @module pi-hashline-edit/core
|
|
30
28
|
*/
|
|
31
29
|
|
|
32
30
|
import { computeLineHash } from "./hash.ts";
|
|
33
|
-
import { detectLineEnding, hasFinalNewline, splitLines } from "./lines.ts";
|
|
34
|
-
import type { Anchor, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
|
|
31
|
+
import { detectLineEnding, hasFinalNewline, lineSeparators, replacementSeparator, splitLines } from "./lines.ts";
|
|
32
|
+
import type { Anchor, AnchorCheck, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
|
|
33
|
+
import { findSortedRangeConflict } from "./ranges.ts";
|
|
35
34
|
|
|
36
35
|
/** Line-level operation: replace the raw lines in the `[lo, hi)` range (0-based, hi exclusive) with newLines. */
|
|
37
36
|
interface SpanOp {
|
|
@@ -40,7 +39,7 @@ interface SpanOp {
|
|
|
40
39
|
newLines: string[];
|
|
41
40
|
}
|
|
42
41
|
|
|
43
|
-
/** Default ±line radius
|
|
42
|
+
/** Default first-pass ±line radius before full-file recovery. */
|
|
44
43
|
const DEFAULT_SHIFT_RADIUS = 15;
|
|
45
44
|
|
|
46
45
|
/**
|
|
@@ -50,8 +49,8 @@ const DEFAULT_SHIFT_RADIUS = 15;
|
|
|
50
49
|
* current snapshot.
|
|
51
50
|
*
|
|
52
51
|
* Recovery holds the ORIGINAL line number fixed and re-hashes each candidate's
|
|
53
|
-
* content
|
|
54
|
-
*
|
|
52
|
+
* content. A matching checksum identifies a candidate, not proof of the
|
|
53
|
+
* original line's identity: short checksums can collide.
|
|
55
54
|
* A returned candidate's anchor uses the candidate's real line number with a
|
|
56
55
|
* hash computed for that line, so it verifies on retry.
|
|
57
56
|
*/
|
|
@@ -69,22 +68,33 @@ function verifyAnchor(
|
|
|
69
68
|
return null;
|
|
70
69
|
}
|
|
71
70
|
|
|
72
|
-
// Shifted recovery: scan ±radius (excluding the already-failed cited line).
|
|
73
71
|
const candidates: { line: number; hash: string }[] = [];
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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);
|
|
80
90
|
}
|
|
81
91
|
}
|
|
82
92
|
|
|
83
93
|
let recovery: AnchorRecovery;
|
|
84
94
|
if (candidates.length === 1) {
|
|
85
|
-
recovery = { kind: "found", newLine: candidates[0].line, newHash: candidates[0].hash };
|
|
95
|
+
recovery = { kind: "found", scope, newLine: candidates[0].line, newHash: candidates[0].hash };
|
|
86
96
|
} else if (candidates.length > 1) {
|
|
87
|
-
recovery = { kind: "ambiguous", candidates };
|
|
97
|
+
recovery = { kind: "ambiguous", scope, candidates };
|
|
88
98
|
} else {
|
|
89
99
|
recovery = { kind: "none" };
|
|
90
100
|
}
|
|
@@ -98,9 +108,27 @@ function verifyAnchor(
|
|
|
98
108
|
}
|
|
99
109
|
|
|
100
110
|
type TranslateResult =
|
|
101
|
-
| { readonly ok: true; readonly op: SpanOp }
|
|
102
|
-
| { readonly ok: false; readonly anchorFailures: AnchorFailure[] }
|
|
103
|
-
| { readonly ok: false; readonly rangeError: string };
|
|
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[] };
|
|
114
|
+
|
|
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" };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
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;
|
|
131
|
+
}
|
|
104
132
|
|
|
105
133
|
/** Translate an Edit into a SpanOp, verifying anchors and ranges against the current lines. */
|
|
106
134
|
function translateEdit(
|
|
@@ -114,69 +142,60 @@ function translateEdit(
|
|
|
114
142
|
case "replace":
|
|
115
143
|
case "delete": {
|
|
116
144
|
const failures: AnchorFailure[] = [];
|
|
145
|
+
const checks: AnchorCheck[] = [];
|
|
117
146
|
const startF = verifyAnchor(lines, edit.start, "anchor", opIndex, edit.op, hashLen, radius);
|
|
147
|
+
checks.push(checkedAnchor(edit, opIndex, "anchor", edit.start, startF));
|
|
118
148
|
if (startF) failures.push(startF);
|
|
119
149
|
let endLine = edit.start.line;
|
|
120
150
|
if (edit.end) {
|
|
121
151
|
const endF = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
|
|
152
|
+
checks.push(checkedAnchor(edit, opIndex, "end", edit.end, endF));
|
|
122
153
|
if (endF) failures.push(endF);
|
|
123
154
|
endLine = edit.end.line;
|
|
124
155
|
}
|
|
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
|
-
}
|
|
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 };
|
|
129
158
|
return {
|
|
130
159
|
ok: true,
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
hi: endLine,
|
|
134
|
-
newLines: edit.op === "delete" ? [] : edit.body,
|
|
135
|
-
},
|
|
160
|
+
checks,
|
|
161
|
+
op: { lo: edit.start.line - 1, hi: endLine, newLines: edit.op === "delete" ? [] : edit.body },
|
|
136
162
|
};
|
|
137
163
|
}
|
|
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
|
-
}
|
|
164
|
+
case "insert_after":
|
|
143
165
|
case "insert_before": {
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
return { ok:
|
|
147
|
-
|
|
148
|
-
|
|
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 } };
|
|
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 } };
|
|
153
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 } };
|
|
154
176
|
}
|
|
155
177
|
}
|
|
156
178
|
|
|
157
|
-
|
|
158
|
-
function
|
|
159
|
-
return
|
|
179
|
+
|
|
180
|
+
function hasInvalidBodyLine(edits: readonly Edit[]): boolean {
|
|
181
|
+
return edits.some((edit) => "body" in edit && edit.body.some((line) => /[\r\n]/.test(line)));
|
|
160
182
|
}
|
|
161
183
|
|
|
162
184
|
/**
|
|
163
185
|
* Apply edits to `text`. Anchors are verified against the current content; on
|
|
164
186
|
* success `touchedLines` gives the 0-based indices of the new-file lines this
|
|
165
187
|
* edit produced. On any anchor mismatch, all failures (with shifted recovery)
|
|
166
|
-
* are collected and returned together — nothing is written.
|
|
188
|
+
* are collected and returned together — nothing is written. Every failure includes
|
|
189
|
+
* per-input anchor checks; input rejection before hashing marks them not_checked.
|
|
167
190
|
*
|
|
168
191
|
* @param text current full file text
|
|
169
192
|
* @param edits parsed edit operations
|
|
170
193
|
* @param hashLen hash length used to verify anchors (default 4)
|
|
171
|
-
* @param shiftRadius ±line radius
|
|
194
|
+
* @param shiftRadius first-pass ±line radius before full-file recovery (default 15; 0 disables recovery)
|
|
172
195
|
*/
|
|
173
|
-
function hasInvalidBodyLine(edits: readonly Edit[]): boolean {
|
|
174
|
-
return edits.some((edit) => "body" in edit && edit.body.some((line) => /[\r\n]/.test(line)));
|
|
175
|
-
}
|
|
176
|
-
|
|
177
196
|
export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius = DEFAULT_SHIFT_RADIUS): ApplyResult {
|
|
178
197
|
if (hasInvalidBodyLine(edits)) {
|
|
179
|
-
return { ok: false, failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line." } };
|
|
198
|
+
return { ok: false, failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line.", checks: inputAnchorChecks(edits, "not_checked") } };
|
|
180
199
|
}
|
|
181
200
|
const lines = splitLines(text);
|
|
182
201
|
const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
@@ -184,10 +203,12 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
|
|
|
184
203
|
|
|
185
204
|
const ops: SpanOp[] = [];
|
|
186
205
|
const anchorFailures: AnchorFailure[] = [];
|
|
206
|
+
const anchorChecks: AnchorCheck[] = [];
|
|
187
207
|
let rangeError: string | null = null;
|
|
188
208
|
|
|
189
209
|
for (let i = 0; i < edits.length; i++) {
|
|
190
210
|
const t = translateEdit(edits[i], i, lines, hashLen, shiftRadius);
|
|
211
|
+
anchorChecks.push(...t.checks);
|
|
191
212
|
if (t.ok) {
|
|
192
213
|
ops.push(t.op);
|
|
193
214
|
} else if ("anchorFailures" in t) {
|
|
@@ -200,44 +221,45 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
|
|
|
200
221
|
// Anchor failures take priority: the model must fix anchors first; range
|
|
201
222
|
// issues among surviving ops are premature until anchors are corrected.
|
|
202
223
|
if (anchorFailures.length > 0) {
|
|
203
|
-
return { ok: false, failure: { kind: "anchor", failures: anchorFailures } };
|
|
224
|
+
return { ok: false, failure: { kind: "anchor", failures: anchorFailures, checks: anchorChecks } };
|
|
204
225
|
}
|
|
205
226
|
if (rangeError !== null) {
|
|
206
|
-
return { ok: false, failure: { kind: "range", message: rangeError } };
|
|
227
|
+
return { ok: false, failure: { kind: "range", message: rangeError, checks: anchorChecks } };
|
|
207
228
|
}
|
|
208
229
|
|
|
209
|
-
// Overlap check: sort ascending by lo; the next op's start must not fall inside the previous op's affected range
|
|
210
230
|
const sorted = [...ops].sort((a, b) => a.lo - b.lo || a.hi - b.hi);
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
}
|
|
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
|
+
};
|
|
221
241
|
}
|
|
222
242
|
|
|
223
243
|
// Mixed line endings: each line carries the separator that FOLLOWED it in
|
|
224
244
|
// the original (its gap), so surviving lines keep theirs byte for byte. New
|
|
225
245
|
// gaps borrow the removed block's separators positionally — the last new
|
|
226
246
|
// line inherits the block's trailing gap, leaving the boundary to the next
|
|
227
|
-
// surviving line unchanged
|
|
228
|
-
//
|
|
229
|
-
const separators = text
|
|
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);
|
|
230
250
|
const separator = ending === "crlf" ? "\r\n" : "\n";
|
|
231
251
|
// Verify legacy anchors above before separating the file BOM from movable line content.
|
|
232
252
|
let result = lines.map((content, i) => ({ content: bom && i === 0 ? content.slice(1) : content, separator: separators[i] ?? "" }));
|
|
233
253
|
for (const op of [...sorted].sort((a, b) => b.lo - a.lo)) {
|
|
234
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);
|
|
235
257
|
const inserted = op.newLines.map((content, i) => ({
|
|
236
258
|
// A copied first-line BOM denotes the existing file header, not a second BOM.
|
|
237
259
|
content: bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
|
|
238
260
|
separator: i === op.newLines.length - 1 && removed.length > 0
|
|
239
261
|
? removed[removed.length - 1].separator
|
|
240
|
-
:
|
|
262
|
+
: replacementSeparator(removedSeparators, i, separator),
|
|
241
263
|
}));
|
|
242
264
|
result.splice(op.lo, op.hi - op.lo, ...inserted);
|
|
243
265
|
}
|
|
@@ -246,29 +268,29 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
|
|
|
246
268
|
content + (i < result.length - 1 || finalNewline ? current || separator : ""),
|
|
247
269
|
).join("");
|
|
248
270
|
if (newText === text) {
|
|
249
|
-
return {
|
|
250
|
-
ok: false,
|
|
251
|
-
failure: {
|
|
252
|
-
kind: "noop",
|
|
253
|
-
message: "edit parsed and applied cleanly but produced no change; body is byte-identical — the bug is elsewhere, re-read first",
|
|
254
|
-
},
|
|
255
|
-
};
|
|
271
|
+
return { ok: true, text, changed: false, touchedLines: [], contextLines: [] };
|
|
256
272
|
}
|
|
257
273
|
|
|
258
274
|
// touchedLines: new-file indices worth re-anchoring — each produced line,
|
|
259
275
|
// and for a pure delete the line that shifted into the gap (so the model
|
|
260
276
|
// gets a fresh anchor for the shifted region).
|
|
261
277
|
const touched: number[] = [];
|
|
278
|
+
const contextLines = new Set<number>();
|
|
262
279
|
let delta = 0;
|
|
263
280
|
for (const op of sorted) {
|
|
264
281
|
const newLo = op.lo + delta;
|
|
265
282
|
if (op.newLines.length > 0) {
|
|
266
|
-
for (let i = 0; i < op.newLines.length; i++)
|
|
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
|
+
}
|
|
267
288
|
} else if (newLo < result.length) {
|
|
268
289
|
touched.push(newLo);
|
|
290
|
+
contextLines.add(newLo);
|
|
269
291
|
}
|
|
270
292
|
delta += op.newLines.length - (op.hi - op.lo);
|
|
271
293
|
}
|
|
272
294
|
|
|
273
|
-
return { ok: true, text: newText, changed: true, touchedLines: touched };
|
|
295
|
+
return { ok: true, text: newText, changed: true, touchedLines: touched, contextLines: [...contextLines] };
|
|
274
296
|
}
|
package/src/core/lines.test.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
|
|
3
|
+
import { createLfTextView, normalizeLineEndings, splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
|
|
4
4
|
|
|
5
5
|
test("splitLines edge cases", () => {
|
|
6
6
|
assert.deepEqual(splitLines(""), []);
|
|
@@ -31,3 +31,14 @@ test("detectLineEnding", () => {
|
|
|
31
31
|
assert.equal(detectLineEnding("a\r\nb\r\n"), "crlf");
|
|
32
32
|
assert.equal(detectLineEnding("a\nb\r\nc\n"), "crlf");
|
|
33
33
|
});
|
|
34
|
+
|
|
35
|
+
test("LF views map every UTF-16 boundary back to original CRLF bytes", () => {
|
|
36
|
+
for (const source of ["", "a\nb", "\uFEFF😀\r\nb\nc\r\n", "\r\n\r\n", "a\rb\r\r\nc"]) {
|
|
37
|
+
const view = createLfTextView(source);
|
|
38
|
+
assert.equal(view.text, normalizeLineEndings(source));
|
|
39
|
+
assert.equal(view.sourceOffset(view.text.length), source.length);
|
|
40
|
+
for (let offset = 0; offset <= view.text.length; offset++) {
|
|
41
|
+
assert.equal(normalizeLineEndings(source.slice(0, view.sourceOffset(offset))), view.text.slice(0, offset));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
});
|
package/src/core/lines.ts
CHANGED
|
@@ -18,6 +18,48 @@
|
|
|
18
18
|
|
|
19
19
|
import type { LineEnding } from "./types.ts";
|
|
20
20
|
|
|
21
|
+
/** Normalize CRLF boundaries to LF; standalone CR remains content. */
|
|
22
|
+
export function normalizeLineEndings(text: string): string {
|
|
23
|
+
return text.replace(/\r\n/g, "\n");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Raw separators in logical-line order, shared by both mutation applicators. */
|
|
27
|
+
export function lineSeparators(text: string): string[] {
|
|
28
|
+
return text.match(/\r?\n/g) ?? [];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** New internal gaps reuse the corresponding old gap, then the last gap or file style. */
|
|
32
|
+
export function replacementSeparator(separators: readonly string[], index: number, fallback: string): string {
|
|
33
|
+
return separators[index] || separators[separators.length - 1] || fallback;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Restore a logical replacement without normalizing it a second time. */
|
|
37
|
+
export function restoreLineEndings(logical: string, original: string, fallback: string): string {
|
|
38
|
+
const separators = lineSeparators(original);
|
|
39
|
+
let index = 0;
|
|
40
|
+
return logical.replace(/\n/g, () => replacementSeparator(separators, index++, fallback));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
|
|
44
|
+
export function createLfTextView(source: string) {
|
|
45
|
+
const removed: number[] = [];
|
|
46
|
+
for (const match of source.matchAll(/\r\n/g)) removed.push(match.index! - removed.length);
|
|
47
|
+
return {
|
|
48
|
+
text: normalizeLineEndings(source),
|
|
49
|
+
sourceOffset(offset: number): number {
|
|
50
|
+
// Count removed CRs strictly before this boundary: a newline starts at its original CR.
|
|
51
|
+
let lo = 0;
|
|
52
|
+
let hi = removed.length;
|
|
53
|
+
while (lo < hi) {
|
|
54
|
+
const mid = Math.floor((lo + hi) / 2);
|
|
55
|
+
if (removed[mid] < offset) lo = mid + 1;
|
|
56
|
+
else hi = mid;
|
|
57
|
+
}
|
|
58
|
+
return offset + lo;
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
21
63
|
/**
|
|
22
64
|
* Split text into lines, normalizing CRLF boundaries and preserving standalone `\r`.
|
|
23
65
|
*
|
|
@@ -30,7 +72,7 @@ import type { LineEnding } from "./types.ts";
|
|
|
30
72
|
*/
|
|
31
73
|
export function splitLines(text: string): string[] {
|
|
32
74
|
if (text === "") return [];
|
|
33
|
-
const normalized = text
|
|
75
|
+
const normalized = normalizeLineEndings(text);
|
|
34
76
|
return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
|
|
35
77
|
}
|
|
36
78
|
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { findSortedRangeConflict, mergeRanges, type HalfOpenRange } from "./ranges.ts";
|
|
4
|
+
|
|
5
|
+
test("conflicts distinguish adjacent ranges from insertions at starts and interiors", () => {
|
|
6
|
+
const cases: [HalfOpenRange[], number | undefined][] = [
|
|
7
|
+
[[], undefined],
|
|
8
|
+
[[[0, 2], [2, 4]], undefined],
|
|
9
|
+
[[[0, 2], [2, 2]], undefined],
|
|
10
|
+
[[[0, 0], [0, 0]], 1],
|
|
11
|
+
[[[0, 0], [0, 2]], 1],
|
|
12
|
+
[[[0, 3], [1, 1]], 1],
|
|
13
|
+
[[[0, 3], [1, 2]], 1],
|
|
14
|
+
[[[0, 1], [1, 2], [1, 3]], 2],
|
|
15
|
+
];
|
|
16
|
+
for (const [ranges, expected] of cases) {
|
|
17
|
+
assert.equal(findSortedRangeConflict(ranges), expected);
|
|
18
|
+
assert.equal(findSortedRangeConflict(ranges.map(([start, end]) => [start + 10, end + 10])), expected);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("range merging preserves input and coalesces overlap, containment, and adjacency", () => {
|
|
23
|
+
const ranges: HalfOpenRange[] = [[7, 9], [1, 3], [2, 3], [3, 5]];
|
|
24
|
+
const before = structuredClone(ranges);
|
|
25
|
+
assert.deepEqual(mergeRanges(ranges), [[1, 5], [7, 9]]);
|
|
26
|
+
assert.deepEqual(ranges, before);
|
|
27
|
+
assert.deepEqual(mergeRanges([]), []);
|
|
28
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Half-open bounds in a caller-selected unit (line indices or string offsets). */
|
|
2
|
+
export type HalfOpenRange = readonly [start: number, end: number];
|
|
3
|
+
|
|
4
|
+
/** Find the first conflicting pair's second index. Input must be sorted by start, then end. */
|
|
5
|
+
export function findSortedRangeConflict(ranges: readonly HalfOpenRange[]): number | undefined {
|
|
6
|
+
for (let i = 1; i < ranges.length; i++) {
|
|
7
|
+
const previous = ranges[i - 1];
|
|
8
|
+
const current = ranges[i];
|
|
9
|
+
// Insertions conflict at a shared start or inside a range, but not at its end.
|
|
10
|
+
if (current[0] < previous[1] || current[0] === previous[0]) return i;
|
|
11
|
+
}
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Merge overlapping or adjacent ranges; callers validate their own units and bounds. */
|
|
16
|
+
export function mergeRanges(ranges: readonly HalfOpenRange[]): HalfOpenRange[] {
|
|
17
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
18
|
+
const result: HalfOpenRange[] = [];
|
|
19
|
+
for (const range of sorted) {
|
|
20
|
+
const previous = result.at(-1);
|
|
21
|
+
if (!previous || range[0] > previous[1]) result.push(range);
|
|
22
|
+
else if (range[1] > previous[1]) result[result.length - 1] = [previous[0], range[1]];
|
|
23
|
+
}
|
|
24
|
+
return result;
|
|
25
|
+
}
|
package/src/core/text.ts
CHANGED
|
@@ -16,3 +16,8 @@ export function decodeEditableText(bytes: Uint8Array): string {
|
|
|
16
16
|
if (bytes.includes(0)) throw new Error("UNSUPPORTED_TEXT: NUL bytes are not editable.");
|
|
17
17
|
return decodeUtf8(bytes);
|
|
18
18
|
}
|
|
19
|
+
|
|
20
|
+
/** Escape regex metacharacters for a standalone literal pattern in JS or ripgrep. */
|
|
21
|
+
export function escapeRegex(text: string): string {
|
|
22
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
23
|
+
}
|
package/src/core/types.ts
CHANGED
|
@@ -26,23 +26,25 @@ export type Edit =
|
|
|
26
26
|
export type LineEnding = "lf" | "crlf";
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
|
-
* Outcome of shifted-anchor recovery.
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* candidate
|
|
33
|
-
*
|
|
34
|
-
*
|
|
29
|
+
* Outcome of shifted-anchor recovery. Search ±radius first; only if there are
|
|
30
|
+
* no candidates, search the rest of the file. Radius 0 disables recovery.
|
|
31
|
+
* Candidate checksums hold the ORIGINAL line number fixed. Because checksums
|
|
32
|
+
* can collide, a match is a candidate rather than proof of identity. Returned
|
|
33
|
+
* anchors use each candidate's actual line number and freshly computed hash.
|
|
34
|
+
* Candidate `scope` records the completed search: local results leave matches
|
|
35
|
+
* outside the window unchecked; full-file results cover the entire snapshot.
|
|
35
36
|
*
|
|
36
|
-
* - `found` — exactly one
|
|
37
|
-
* with the provided anchor.
|
|
38
|
-
* - `ambiguous` — several
|
|
39
|
-
*
|
|
40
|
-
* - `none` —
|
|
37
|
+
* - `found` — exactly one line matches in the selected search scope; the caller
|
|
38
|
+
* checks its content before resending with the provided anchor.
|
|
39
|
+
* - `ambiguous` — several lines match; the caller inspects the candidates
|
|
40
|
+
* and chooses the intended target.
|
|
41
|
+
* - `none` — no candidate found, or recovery disabled; re-read.
|
|
41
42
|
*/
|
|
42
43
|
export type AnchorRecovery =
|
|
43
|
-
| { readonly kind: "found"; readonly newLine: number; readonly newHash: string }
|
|
44
|
+
| { readonly kind: "found"; readonly scope: "local" | "full-file"; readonly newLine: number; readonly newHash: string }
|
|
44
45
|
| {
|
|
45
46
|
readonly kind: "ambiguous";
|
|
47
|
+
readonly scope: "local" | "full-file";
|
|
46
48
|
readonly candidates: ReadonlyArray<{ readonly line: number; readonly hash: string }>;
|
|
47
49
|
}
|
|
48
50
|
| { readonly kind: "none" };
|
|
@@ -64,17 +66,31 @@ export interface AnchorFailure {
|
|
|
64
66
|
readonly current: { readonly hash: string; readonly content: string } | null;
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* Record for one supplied anchor in the immutable apply snapshot.
|
|
71
|
+
* not_checked means input validation rejected the batch before hashing.
|
|
72
|
+
*/
|
|
73
|
+
export interface AnchorCheck {
|
|
74
|
+
readonly opIndex: number;
|
|
75
|
+
readonly which: "anchor" | "end";
|
|
76
|
+
readonly op: Edit["op"];
|
|
77
|
+
readonly cited: Anchor;
|
|
78
|
+
readonly status: "matched" | "mismatched" | "not_checked";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Batch-level failure. Anchor checks describe only checksum validation in this snapshot. */
|
|
68
82
|
export type ApplyFailure =
|
|
69
|
-
| { readonly kind: "anchor"; readonly failures: readonly AnchorFailure[] }
|
|
70
|
-
| { readonly kind: "input" | "range"
|
|
83
|
+
| { readonly kind: "anchor"; readonly failures: readonly AnchorFailure[]; readonly checks: readonly AnchorCheck[] }
|
|
84
|
+
| { readonly kind: "input" | "range"; readonly message: string; readonly checks: readonly AnchorCheck[] };
|
|
71
85
|
|
|
72
86
|
/**
|
|
73
|
-
* Apply result. On success, `touchedLines` lists
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
87
|
+
* Apply result. On success, `touchedLines` lists 0-based NEW-file indices to
|
|
88
|
+
* re-anchor. `contextLines` identifies deletion successors among those lines;
|
|
89
|
+
* callers retain their content while compacting anchors for caller-supplied rows.
|
|
90
|
+
* Byte-identical output succeeds with changed=false and empty anchor lists.
|
|
91
|
+
* On failure, `failure` is either the collected set of anchor failures
|
|
92
|
+
* (each with recovery) or an input/range error, plus per-input anchor checks.
|
|
93
|
+
* Nothing is written on failure.
|
|
78
94
|
*/
|
|
79
95
|
export type ApplyResult =
|
|
80
96
|
| {
|
|
@@ -82,5 +98,6 @@ export type ApplyResult =
|
|
|
82
98
|
readonly text: string;
|
|
83
99
|
readonly changed: boolean;
|
|
84
100
|
readonly touchedLines: readonly number[];
|
|
101
|
+
readonly contextLines: readonly number[];
|
|
85
102
|
}
|
|
86
103
|
| { readonly ok: false; readonly failure: ApplyFailure };
|