@criogaid/pi-hashline-edit 0.1.2 → 0.2.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 +67 -21
- package/package.json +1 -1
- package/src/core/apply.test.ts +85 -8
- package/src/core/apply.ts +99 -79
- 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 +76 -1
- package/src/pi/action-fusion.test.ts +1 -1
- package/src/pi/action-fusion.ts +9 -21
- package/src/pi/anchor-format.test.ts +30 -0
- package/src/pi/anchor-format.ts +28 -0
- package/src/pi/config.test.ts +6 -9
- package/src/pi/config.ts +4 -4
- package/src/pi/edit-tool.ts +90 -99
- package/src/pi/execute.test.ts +240 -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 +3 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/grep-tool.ts +75 -48
- package/src/pi/grep.test.ts +67 -3
- package/src/pi/mutation-result.ts +46 -9
- package/src/pi/read-tool.ts +7 -10
- package/src/pi/registration.test.ts +15 -2
- package/src/pi/render.test.ts +24 -0
- package/src/pi/render.ts +18 -4
- package/src/pi/replace-tool.ts +134 -130
- package/src/pi/replace.test.ts +118 -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 +9 -11
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/state.ts +2 -3
- package/src/pi/write-tool.ts +10 -44
- 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
31
|
import { detectLineEnding, hasFinalNewline, splitLines } from "./lines.ts";
|
|
34
|
-
import type { Anchor, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.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,24 +221,23 @@ 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
|
|
@@ -246,29 +266,29 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
|
|
|
246
266
|
content + (i < result.length - 1 || finalNewline ? current || separator : ""),
|
|
247
267
|
).join("");
|
|
248
268
|
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
|
-
};
|
|
269
|
+
return { ok: true, text, changed: false, touchedLines: [], contextLines: [] };
|
|
256
270
|
}
|
|
257
271
|
|
|
258
272
|
// touchedLines: new-file indices worth re-anchoring — each produced line,
|
|
259
273
|
// and for a pure delete the line that shifted into the gap (so the model
|
|
260
274
|
// gets a fresh anchor for the shifted region).
|
|
261
275
|
const touched: number[] = [];
|
|
276
|
+
const contextLines = new Set<number>();
|
|
262
277
|
let delta = 0;
|
|
263
278
|
for (const op of sorted) {
|
|
264
279
|
const newLo = op.lo + delta;
|
|
265
280
|
if (op.newLines.length > 0) {
|
|
266
|
-
for (let i = 0; i < op.newLines.length; i++)
|
|
281
|
+
for (let i = 0; i < op.newLines.length; i++) {
|
|
282
|
+
touched.push(newLo + i);
|
|
283
|
+
// An adjacent replacement may supply the deletion successor itself.
|
|
284
|
+
contextLines.delete(newLo + i);
|
|
285
|
+
}
|
|
267
286
|
} else if (newLo < result.length) {
|
|
268
287
|
touched.push(newLo);
|
|
288
|
+
contextLines.add(newLo);
|
|
269
289
|
}
|
|
270
290
|
delta += op.newLines.length - (op.hi - op.lo);
|
|
271
291
|
}
|
|
272
292
|
|
|
273
|
-
return { ok: true, text: newText, changed: true, touchedLines: touched };
|
|
293
|
+
return { ok: true, text: newText, changed: true, touchedLines: touched, contextLines: [...contextLines] };
|
|
274
294
|
}
|
|
@@ -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 };
|
|
@@ -10,7 +10,11 @@ import { join } from "node:path";
|
|
|
10
10
|
import { rgPath } from "@vscode/ripgrep";
|
|
11
11
|
import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
|
|
12
12
|
import { makeEditOverride } from "../pi/edit-tool.ts";
|
|
13
|
+
import { makeReadOverride } from "../pi/read-tool.ts";
|
|
14
|
+
import { makeWriteOverride } from "../pi/write-tool.ts";
|
|
15
|
+
import { makeReplaceTool } from "../pi/replace-tool.ts";
|
|
13
16
|
import { COMMON_RG_ARGS, createLinePredicate, resolveIgnoreCase, runRg } from "../pi/rg-line-filter.ts";
|
|
17
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
14
18
|
|
|
15
19
|
const REGEX_MODE = { engine: "default", multiline: false, literal: false } as const;
|
|
16
20
|
|
|
@@ -151,7 +155,7 @@ test("real rg validates its own regex syntax and limits automatic literal fallba
|
|
|
151
155
|
for (const pattern of ["queueTool(", "foo(?=bar)"]) {
|
|
152
156
|
const result: any = await tool.execute("0", { pattern }, undefined, undefined);
|
|
153
157
|
assert.ok(result.content[0].text.includes(`│${pattern}`));
|
|
154
|
-
assert.match(result.content[0].text, /Invalid regex; searched
|
|
158
|
+
assert.match(result.content[0].text, /Invalid regex; searched the pattern as literal text/);
|
|
155
159
|
await assert.rejects(
|
|
156
160
|
tool.execute("0", { pattern, literal: false }, undefined, undefined),
|
|
157
161
|
/regex parse error/,
|
|
@@ -162,6 +166,12 @@ test("real rg validates its own regex syntax and limits automatic literal fallba
|
|
|
162
166
|
const explicit: any = await tool.execute("0", { pattern: "queueTool(", literal: true }, undefined, undefined);
|
|
163
167
|
assert.match(explicit.content[0].text, /│queueTool\(/);
|
|
164
168
|
assert.doesNotMatch(explicit.content[0].text, /Invalid regex/);
|
|
169
|
+
for (const params of [
|
|
170
|
+
{ pattern: ["queueTool(", "\\bfoo\\b"] },
|
|
171
|
+
{ pattern: "queueTool(", excludePattern: "^\\s*//" },
|
|
172
|
+
]) {
|
|
173
|
+
await assert.rejects(tool.execute("0", params, undefined, undefined), /Invalid regex in compound query/);
|
|
174
|
+
}
|
|
165
175
|
} finally {
|
|
166
176
|
await rm(directory, { recursive: true, force: true });
|
|
167
177
|
}
|
|
@@ -435,3 +445,68 @@ test("real rg accepts wildcard-only regexes and preserves limits and literal mod
|
|
|
435
445
|
await rm(directory, { recursive: true, force: true });
|
|
436
446
|
}
|
|
437
447
|
});
|
|
448
|
+
|
|
449
|
+
test("tools share physical lines and anchors across text representations", async () => {
|
|
450
|
+
const directory = await mkdtemp(join(tmpdir(), "hl-text-integration-"));
|
|
451
|
+
const call = (tool: any, params: any) => tool.execute("0", params, undefined, undefined);
|
|
452
|
+
const rows = (result: any): string[] => result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line));
|
|
453
|
+
try {
|
|
454
|
+
const file = join(directory, "fixture.txt");
|
|
455
|
+
for (const before of [
|
|
456
|
+
"a\nold\n",
|
|
457
|
+
"a\r\nold\r\n",
|
|
458
|
+
"\uFEFFa\r\nold\nkeep\r\n",
|
|
459
|
+
"a\rb\nold\n",
|
|
460
|
+
"a\rb\nold",
|
|
461
|
+
]) {
|
|
462
|
+
await call(makeWriteOverride(directory), { path: file, content: before });
|
|
463
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
464
|
+
const read = await call(makeReadOverride(directory), { path: file });
|
|
465
|
+
const grep = await call(makeGrepOverrideWithBackend(directory, {}), { path: file, pattern: "old", context: 2 });
|
|
466
|
+
assert.deepEqual(rows(grep), rows(read));
|
|
467
|
+
if (before.includes("a\rb")) assert.match(rows(read)[0], /│a␍b$/);
|
|
468
|
+
const anchor = rows(grep)[1].split("│")[0];
|
|
469
|
+
const edit = await call(makeEditOverride(directory), { path: file, edits: [{ op: "replace", anchor, body: ["new"] }] });
|
|
470
|
+
assert.equal(await readFile(file, "utf8"), before.replace("old", "new"));
|
|
471
|
+
assert.equal(edit.details.firstChangedLine, 2);
|
|
472
|
+
assert.match(edit.details.diff, /^-2 old/m);
|
|
473
|
+
assert.match(edit.details.diff, /^\+2 new/m);
|
|
474
|
+
assert.ok(!edit.details.diff.includes("\r"));
|
|
475
|
+
if (before.includes("a\rb")) assert.ok(edit.details.patch.includes(" a\rb\n"));
|
|
476
|
+
const editedRead = await call(makeReadOverride(directory), { path: file });
|
|
477
|
+
assert.equal(rows(edit)[0], rows(editedRead)[1].split("│")[0]);
|
|
478
|
+
const replaced = await call(makeReplaceTool(directory), { path: file, find: "new", replace: "next" });
|
|
479
|
+
assert.equal(await readFile(file, "utf8"), before.replace("old", "next"));
|
|
480
|
+
assert.equal(replaced.details.firstChangedLine, 2);
|
|
481
|
+
const replacedRead = await call(makeReadOverride(directory), { path: file });
|
|
482
|
+
assert.equal(rows(replaced)[0], rows(replacedRead)[1].split("│")[0]);
|
|
483
|
+
}
|
|
484
|
+
} finally {
|
|
485
|
+
await rm(directory, { recursive: true, force: true });
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
test("long-line previews expose real rg hits across engines and preserve full-line anchors", async () => {
|
|
490
|
+
const directory = await mkdtemp(join(tmpdir(), "hl-grep-preview-"));
|
|
491
|
+
try {
|
|
492
|
+
const long = "😀界".repeat(220) + "NEEDLE" + "tail".repeat(200);
|
|
493
|
+
const context = "x" + "😀".repeat(400);
|
|
494
|
+
await writeFile(join(directory, "long.txt"), `${long}\r\nfollow\r\n${context}\r\n`);
|
|
495
|
+
const tool = makeGrepOverrideWithBackend(directory, {});
|
|
496
|
+
for (const params of [
|
|
497
|
+
{ pattern: "NEEDLE" },
|
|
498
|
+
{ pattern: ["NEEDLE", "tail"], matchMode: "all", excludePattern: "absent" },
|
|
499
|
+
{ pattern: "NEEDLE(?=tail)", pcre2: true },
|
|
500
|
+
{ pattern: "NEEDLE(?:tail)+\\r?\\nfollow", multiline: true },
|
|
501
|
+
]) {
|
|
502
|
+
const result: any = await tool.execute("preview", { ...params, context: 2 }, undefined, undefined);
|
|
503
|
+
const output = result.content[0].text;
|
|
504
|
+
const row = output.split("\n").find((line: string) => line.startsWith("1#"));
|
|
505
|
+
assert.ok(row.startsWith(`1#${computeLineHash(1, long)}│[partial, columns `));
|
|
506
|
+
assert.ok(row.includes("NEEDLE"));
|
|
507
|
+
assert.equal(Buffer.from(row).toString("utf8"), row);
|
|
508
|
+
assert.ok(output.includes(`3#${computeLineHash(3, context)}│[partial, columns 1-499]`));
|
|
509
|
+
assert.match(output, /anchors hash full lines/);
|
|
510
|
+
}
|
|
511
|
+
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
512
|
+
});
|
|
@@ -17,7 +17,7 @@ async function tempDir(): Promise<string> {
|
|
|
17
17
|
|
|
18
18
|
const ctx = (cwd: string) => ({ cwd }) as any;
|
|
19
19
|
|
|
20
|
-
test("
|
|
20
|
+
test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
|
|
21
21
|
const fusion = createActionFusionExecutor();
|
|
22
22
|
for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
|
|
23
23
|
const disabled = makeTool("/tmp") as any;
|
package/src/pi/action-fusion.ts
CHANGED
|
@@ -54,13 +54,8 @@ type CommandRunner = (toolCallId: string, input: ThenRunInput, signal: AbortSign
|
|
|
54
54
|
type MutationResult<TDetails> = AgentToolResult<TDetails>;
|
|
55
55
|
type MutationFinalizer<TDetails> = (result: MutationResult<TDetails>, publishAnchors: boolean) => MutationResult<TDetails>;
|
|
56
56
|
|
|
57
|
-
function staleAnchorNotice
|
|
58
|
-
|
|
59
|
-
return [
|
|
60
|
-
`${THEN_RUN_STALE} Target freshness was not confirmed unchanged after then_run.`,
|
|
61
|
-
"Pre-command anchors are omitted. Re-read before further edits.",
|
|
62
|
-
...(typeof publishedRevision === "string" ? ["The published revision may not describe the final file."] : []),
|
|
63
|
-
].join("\n");
|
|
57
|
+
function staleAnchorNotice(): string {
|
|
58
|
+
return `${THEN_RUN_STALE} Pre-command anchors are omitted: target freshness is unconfirmed. Re-read before further edits.`;
|
|
64
59
|
}
|
|
65
60
|
|
|
66
61
|
function errorText(error: unknown): string {
|
|
@@ -96,10 +91,8 @@ export class ActionFusionError extends Error {
|
|
|
96
91
|
|
|
97
92
|
constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown }) {
|
|
98
93
|
const fileState = state.publication === "PUBLISHED" ? "File changes are saved."
|
|
99
|
-
: state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain
|
|
100
|
-
|
|
101
|
-
? " Re-read the file before further edits." : "";
|
|
102
|
-
super(`${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.${nextStep}`, options);
|
|
94
|
+
: state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
|
|
95
|
+
super(`${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.`, options);
|
|
103
96
|
// Pi exposes error.message to the model, but does not serialize Error.cause.
|
|
104
97
|
if (options?.cause !== undefined) this.message += `\n${errorText(options.cause)}`;
|
|
105
98
|
this.name = "ActionFusionError";
|
|
@@ -268,14 +261,8 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
|
|
|
268
261
|
|
|
269
262
|
const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
|
|
270
263
|
report("succeeded", publication, freshness, output);
|
|
271
|
-
const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation, freshness === "unchanged") : mutationResult;
|
|
272
|
-
const commandText = freshness
|
|
273
|
-
? (output ? `${THEN_RUN_SUCCEEDED}\n${output}` : THEN_RUN_SUCCEEDED)
|
|
274
|
-
: `${THEN_RUN_SUCCEEDED}\n${
|
|
275
|
-
finalizeMutation
|
|
276
|
-
? staleAnchorNotice(finalized)
|
|
277
|
-
: `${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.`
|
|
278
|
-
}${output ? `\n${output}` : ""}`;
|
|
264
|
+
const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation, freshness === "unchanged", staleAnchorNotice()) : mutationResult;
|
|
265
|
+
const commandText = `${THEN_RUN_SUCCEEDED}${!finalizeMutation && freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.` : ""}${output ? `\n${output}` : ""}`;
|
|
279
266
|
return {
|
|
280
267
|
...finalized,
|
|
281
268
|
details: { ...(finalized.details as object ?? {}), actionFusion },
|
|
@@ -287,14 +274,15 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
|
|
|
287
274
|
error instanceof ActionFusionError ? error.freshness : "unknown", errorText(error));
|
|
288
275
|
// A completed mutation remains successful; command failure belongs to its own card.
|
|
289
276
|
if (completedMutation && error instanceof ActionFusionError) {
|
|
290
|
-
const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged") : completedMutation;
|
|
291
|
-
const anchorNotice = finalizeMutation && error.freshness !== "unchanged" ? `\n${
|
|
277
|
+
const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged", staleAnchorNotice()) : completedMutation;
|
|
278
|
+
const anchorNotice = !finalizeMutation && error.freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read before further edits; previous anchors may no longer match.` : "";
|
|
292
279
|
return {
|
|
293
280
|
...finalized,
|
|
294
281
|
details: { ...(finalized.details as object ?? {}), actionFusion: { publication: error.publication, command: error.command, freshness: error.freshness } satisfies ActionFusionDetails },
|
|
295
282
|
content: [...finalized.content, { type: "text", text: `${error.message}${anchorNotice}` }],
|
|
296
283
|
} as MutationResult<TDetails>;
|
|
297
284
|
}
|
|
285
|
+
if (error instanceof ActionFusionError && error.publication !== "NOT_PUBLISHED") error.message += "\nRe-read before retrying.";
|
|
298
286
|
if (progressFailure && error instanceof Error) error.message += `\nProgress reporting failed: ${progressFailure}`;
|
|
299
287
|
throw error;
|
|
300
288
|
}).then((result) => progressFailure ? {
|