@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
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
4
|
+
import { ANCHOR_PATTERN, createAnchorFormatter } from "./anchor-format.ts";
|
|
5
|
+
import { getState } from "./state.ts";
|
|
6
|
+
|
|
7
|
+
test("anchor formatter snapshots configured hash length and hashes undisplayed content", () => {
|
|
8
|
+
const state = getState();
|
|
9
|
+
const previous = state.config;
|
|
10
|
+
try {
|
|
11
|
+
state.config = { ...previous, hashLen: 6 };
|
|
12
|
+
const formatter = createAnchorFormatter();
|
|
13
|
+
state.config = { ...previous, hashLen: 4 };
|
|
14
|
+
|
|
15
|
+
assert.equal(formatter.hashLen, 6);
|
|
16
|
+
assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
|
|
17
|
+
assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
|
|
18
|
+
assert.match(formatter.token(3, "full content"), new RegExp(ANCHOR_PATTERN));
|
|
19
|
+
assert.equal(formatter.row(3, "full content", "full…"), `3#${computeLineHash(3, "full content", 6)}│full…`);
|
|
20
|
+
assert.equal(createAnchorFormatter().hashLen, 4);
|
|
21
|
+
} finally {
|
|
22
|
+
state.config = previous;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("anchor rows expose carriage returns while checksums retain source content", () => {
|
|
27
|
+
const formatter = createAnchorFormatter(4);
|
|
28
|
+
assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
|
|
29
|
+
assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
|
|
30
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
2
|
+
import { getState } from "./state.ts";
|
|
3
|
+
|
|
4
|
+
export const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
|
|
5
|
+
|
|
6
|
+
/** Anchor serialization bound to one hash-length snapshot. */
|
|
7
|
+
export interface AnchorFormatter {
|
|
8
|
+
readonly hashLen: number;
|
|
9
|
+
reference(line: number, hash: string): string;
|
|
10
|
+
token(line: number, content: string): string;
|
|
11
|
+
row(line: number, content: string, displayContent?: string): string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Make CR visible without changing the source text used for checksums or patches. */
|
|
15
|
+
export function displayCarriageReturns(text: string): string {
|
|
16
|
+
return text.replace(/\r/g, "␍");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createAnchorFormatter(hashLen = getState().config.hashLen): AnchorFormatter {
|
|
20
|
+
const reference = (line: number, hash: string) => `${line}#${hash}`;
|
|
21
|
+
const token = (line: number, content: string) => reference(line, computeLineHash(line, content, hashLen));
|
|
22
|
+
return {
|
|
23
|
+
hashLen,
|
|
24
|
+
token,
|
|
25
|
+
reference,
|
|
26
|
+
row: (line, content, displayContent = content) => `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
|
|
27
|
+
};
|
|
28
|
+
}
|
package/src/pi/config.test.ts
CHANGED
|
@@ -5,17 +5,14 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { test } from "node:test";
|
|
6
6
|
import { loadConfig } from "./config.ts";
|
|
7
7
|
|
|
8
|
-
test("actionFusion defaults
|
|
8
|
+
test("actionFusion defaults on and honors explicit disabling", async () => {
|
|
9
9
|
const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
|
|
10
10
|
try {
|
|
11
11
|
await mkdir(join(root, ".pi"));
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
assert.equal(config.actionFusion, true);
|
|
17
|
-
assert.equal(config.hashLen, 4);
|
|
18
|
-
assert.equal(config.shiftRadius, 15);
|
|
12
|
+
for (const [actionFusion, expected] of [[undefined, true], [false, false], [true, true], [null, true], ["false", true], [0, true]]) {
|
|
13
|
+
await writeFile(join(root, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion } }));
|
|
14
|
+
assert.deepEqual(loadConfig(root), { enabled: true, actionFusion: expected, hashLen: 4, shiftRadius: 15 });
|
|
15
|
+
}
|
|
19
16
|
} finally {
|
|
20
17
|
await rm(root, { recursive: true, force: true });
|
|
21
18
|
}
|
|
@@ -28,7 +25,7 @@ test("config rejects fractional values and tolerates malformed settings shapes",
|
|
|
28
25
|
const path = join(root, ".pi", "settings.json");
|
|
29
26
|
for (const value of [3.5, -1, "4", null]) {
|
|
30
27
|
await writeFile(path, JSON.stringify({ hashlineEdit: { hashLen: value, shiftRadius: value } }));
|
|
31
|
-
assert.deepEqual(loadConfig(root), { enabled: true, actionFusion:
|
|
28
|
+
assert.deepEqual(loadConfig(root), { enabled: true, actionFusion: true, hashLen: 4, shiftRadius: 15 });
|
|
32
29
|
}
|
|
33
30
|
for (const rootValue of [null, [], 42, "settings", { hashlineEdit: [] }, { hashlineEdit: "invalid" }]) {
|
|
34
31
|
await writeFile(path, JSON.stringify(rootValue));
|
package/src/pi/config.ts
CHANGED
|
@@ -13,15 +13,15 @@ import * as path from "node:path";
|
|
|
13
13
|
export interface HashlineEditConfig {
|
|
14
14
|
/** Master switch: when false the extension registers no tools — pi's built-ins remain. */
|
|
15
15
|
enabled: boolean;
|
|
16
|
-
/**
|
|
16
|
+
/** Expose optional commands after edit/replace/write. Enabled by default; false disables them. */
|
|
17
17
|
actionFusion: boolean;
|
|
18
18
|
/** Line hash length (default 4). */
|
|
19
19
|
hashLen: number;
|
|
20
|
-
/** ±line radius
|
|
20
|
+
/** First-pass ±line radius before full-file recovery (default 15; 0 disables recovery). */
|
|
21
21
|
shiftRadius: number;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion:
|
|
24
|
+
export const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion: true, hashLen: 4, shiftRadius: 15 };
|
|
25
25
|
|
|
26
26
|
/** Parse JSON directly without stripping comments (standard JSON forbids comments; on error fall back to default). */
|
|
27
27
|
function readSettings(filePath: string): Record<string, unknown> {
|
|
@@ -45,7 +45,7 @@ export function loadConfig(cwd?: string): HashlineEditConfig {
|
|
|
45
45
|
const raw = value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
46
46
|
return {
|
|
47
47
|
enabled: typeof raw.enabled === "boolean" ? raw.enabled : DEFAULT_CONFIG.enabled,
|
|
48
|
-
actionFusion: raw.actionFusion ===
|
|
48
|
+
actionFusion: typeof raw.actionFusion === "boolean" ? raw.actionFusion : DEFAULT_CONFIG.actionFusion,
|
|
49
49
|
hashLen:
|
|
50
50
|
typeof raw.hashLen === "number" && Number.isInteger(raw.hashLen) && raw.hashLen >= 2 && raw.hashLen <= 8
|
|
51
51
|
? raw.hashLen
|
package/src/pi/edit-tool.ts
CHANGED
|
@@ -19,25 +19,26 @@
|
|
|
19
19
|
* @module pi-hashline-edit/pi
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import {
|
|
22
|
+
import { truncateHead, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
23
23
|
import { Type, type Static } from "typebox";
|
|
24
|
-
import { Text } from "@earendil-works/pi-tui";
|
|
25
|
-
import { readFile } from "node:fs/promises";
|
|
26
24
|
import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
27
|
-
import {
|
|
28
|
-
import { applyEdits
|
|
25
|
+
import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
|
|
26
|
+
import { applyEdits } from "../core/index.ts";
|
|
29
27
|
import { splitLines } from "../core/lines.ts";
|
|
30
28
|
import type { ApplyFailure, Edit } from "../core/types.ts";
|
|
31
29
|
import { canonicalPath } from "./read-tool.ts";
|
|
32
30
|
import { getState } from "./state.ts";
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
31
|
+
import { ANCHOR_PATTERN, createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
|
|
32
|
+
import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
33
|
+
import { formatAmbiguousCandidateNeighborhoods, MAX_AMBIGUOUS_CANDIDATES, MAX_RECOVERY_CANDIDATE_BYTES } from "./failure-context.ts";
|
|
34
|
+
import { appendMutationAnchors, finalizeMutationResult, formatMutationAnchors, generateMutationDetails, postProcessMutation } from "./mutation-result.ts";
|
|
36
35
|
|
|
37
|
-
/**
|
|
38
|
-
|
|
36
|
+
/** Keep independent byte budgets for failure details and input-anchor checks. */
|
|
37
|
+
function boundDiagnostic(message: string, notice: string): string {
|
|
38
|
+
const bounded = truncateHead(message, { maxBytes: 16 * 1024 - Buffer.byteLength(notice) });
|
|
39
|
+
return bounded.content + (bounded.truncated ? notice : "");
|
|
40
|
+
}
|
|
39
41
|
|
|
40
|
-
const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
|
|
41
42
|
|
|
42
43
|
function anchorRef(description: string) {
|
|
43
44
|
return Type.Optional(Type.String({ pattern: ANCHOR_PATTERN, description }));
|
|
@@ -91,14 +92,17 @@ type EditParams = Omit<Static<typeof editSchema>, "then_run"> & { then_run?: The
|
|
|
91
92
|
|
|
92
93
|
type EditOpInput = Static<typeof editOpSchema>;
|
|
93
94
|
|
|
94
|
-
/** Format
|
|
95
|
-
function
|
|
95
|
+
/** Format failure mappings and complete unique-candidate rows within the detail budget. */
|
|
96
|
+
function formatFailureDetails(
|
|
96
97
|
failure: ApplyFailure,
|
|
97
|
-
snapshot: Readonly<{ currentText: string;
|
|
98
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
99
|
+
candidateLines: ReadonlySet<number>,
|
|
98
100
|
): string {
|
|
99
101
|
if (failure.kind !== "anchor") return failure.message;
|
|
100
102
|
|
|
101
103
|
const lines: string[] = [];
|
|
104
|
+
const currentLines = splitLines(snapshot.currentText);
|
|
105
|
+
const shownCandidates = new Set(candidateLines);
|
|
102
106
|
let found = 0;
|
|
103
107
|
let ambiguous = 0;
|
|
104
108
|
let none = 0;
|
|
@@ -106,21 +110,35 @@ function formatFailure(
|
|
|
106
110
|
if (f.recovery.kind === "found") found++;
|
|
107
111
|
else if (f.recovery.kind === "ambiguous") ambiguous++;
|
|
108
112
|
else none++;
|
|
109
|
-
if (lines.length >= MAX_FAILURE_DETAILS) continue;
|
|
110
113
|
const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
|
|
114
|
+
const search = f.recovery.kind === "none" ? "" : f.recovery.scope === "local"
|
|
115
|
+
? "Search: local; matches outside the window were not checked." : "Search: full file.";
|
|
111
116
|
switch (f.recovery.kind) {
|
|
112
|
-
case "found":
|
|
113
|
-
|
|
117
|
+
case "found": {
|
|
118
|
+
const content = currentLines[f.recovery.newLine - 1];
|
|
119
|
+
const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
|
|
120
|
+
const row = content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
|
|
121
|
+
let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
|
|
122
|
+
if (!shownCandidates.has(f.recovery.newLine)) {
|
|
123
|
+
if (content !== undefined && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
|
|
124
|
+
detail += `\n${row}`;
|
|
125
|
+
shownCandidates.add(f.recovery.newLine);
|
|
126
|
+
} else {
|
|
127
|
+
detail += ` Candidate content exceeds ${MAX_RECOVERY_CANDIDATE_BYTES} bytes.`;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
lines.push(detail);
|
|
114
131
|
break;
|
|
132
|
+
}
|
|
115
133
|
case "ambiguous": {
|
|
116
|
-
const list = f.recovery.candidates.slice(0,
|
|
117
|
-
const more = f.recovery.candidates.length >
|
|
118
|
-
lines.push(`• ${where}: ambiguous checksum matches
|
|
134
|
+
const list = f.recovery.candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES).map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`).join(" / ");
|
|
135
|
+
const more = f.recovery.candidates.length > MAX_AMBIGUOUS_CANDIDATES ? ` (${f.recovery.candidates.length - MAX_AMBIGUOUS_CANDIDATES} more candidates omitted)` : "";
|
|
136
|
+
lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
|
|
119
137
|
break;
|
|
120
138
|
}
|
|
121
139
|
case "none":
|
|
122
140
|
lines.push(
|
|
123
|
-
`• ${where}:
|
|
141
|
+
`• ${where}: no checksum-matching candidate found. Use read to inspect the current file before retrying.` +
|
|
124
142
|
(f.current === null ? " Cited line is out of range." : ""),
|
|
125
143
|
);
|
|
126
144
|
break;
|
|
@@ -134,11 +152,33 @@ function formatFailure(
|
|
|
134
152
|
`Anchor mismatch: ${parts.join(", ")}.`,
|
|
135
153
|
"No changes written by this edit batch.",
|
|
136
154
|
...lines,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
155
|
+
].join("\n");
|
|
156
|
+
return boundDiagnostic(message, "\nDiagnostic output truncated at 16 KiB.");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
|
|
160
|
+
const rows = failure.checks.map((check) =>
|
|
161
|
+
`op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
|
|
162
|
+
);
|
|
163
|
+
const message = [
|
|
164
|
+
"Input-anchor checks (this snapshot):",
|
|
165
|
+
...rows,
|
|
166
|
+
"Anchor checks only; retries revalidate.",
|
|
167
|
+
].join("\n");
|
|
168
|
+
return boundDiagnostic(message, "\nAnchor-check output truncated at 16 KiB; omitted entries are not implied matched.");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Keep validation status and observation context visible even when failure details are truncated. */
|
|
172
|
+
function formatFailure(
|
|
173
|
+
failure: ApplyFailure,
|
|
174
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
175
|
+
): string {
|
|
176
|
+
const candidateNeighborhoods = failure.kind === "anchor"
|
|
177
|
+
? formatAmbiguousCandidateNeighborhoods(snapshot.currentText, failure.failures, snapshot.anchors)
|
|
178
|
+
: { text: "", shownLines: new Set<number>() };
|
|
179
|
+
const guidance = failure.kind === "anchor"
|
|
180
|
+
? "\nCheck the intended target before retrying; use read or grep for omitted or additional context." : "";
|
|
181
|
+
return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}\n${formatAnchorChecks(failure, snapshot.anchors)}${candidateNeighborhoods.text}${guidance}`;
|
|
142
182
|
}
|
|
143
183
|
|
|
144
184
|
/** Translate JSON edit ops into core Edit[]. Validates conditional required fields (anchor/body per op). */
|
|
@@ -177,12 +217,12 @@ function toCoreEdits(ops: readonly EditOpInput[]): { ok: true; edits: Edit[] } |
|
|
|
177
217
|
}
|
|
178
218
|
|
|
179
219
|
/**
|
|
180
|
-
*
|
|
181
|
-
*
|
|
220
|
+
* Return compact tokens for changed caller-supplied rows, retaining content for deletion successors.
|
|
221
|
+
* Uses the applicator's final indices so mixed batches do not need a second position calculation.
|
|
182
222
|
*/
|
|
183
|
-
function formatUpdatedAnchors(newText: string, touched: readonly number[],
|
|
223
|
+
function formatUpdatedAnchors(before: string, newText: string, touched: readonly number[], contextLines: readonly number[], anchors: AnchorFormatter): string {
|
|
184
224
|
const idxs = [...new Set(touched)].sort((a, b) => a - b);
|
|
185
|
-
return formatMutationAnchors(splitLines(newText), idxs,
|
|
225
|
+
return formatMutationAnchors(splitLines(before), splitLines(newText), idxs, anchors, "Updated anchors:", new Set(contextLines));
|
|
186
226
|
}
|
|
187
227
|
|
|
188
228
|
/** Call-header line: `edit path — N ops: op`, plus `+N -N` once the result's diff counts are known. */
|
|
@@ -202,24 +242,18 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
202
242
|
name: "edit" as const,
|
|
203
243
|
label: "edit",
|
|
204
244
|
description:
|
|
205
|
-
"Edit file lines using content-verified anchors. Returns fresh anchors for subsequent edits.
|
|
245
|
+
"Edit file lines using content-verified anchors. Returns fresh anchors for subsequent edits. Anchor failures report input-anchor status and bounded current-file context. Inspect recovery candidates before retrying; retries always revalidate anchors and never run automatically.",
|
|
206
246
|
promptSnippet: "Edit file lines using verified anchors",
|
|
207
247
|
promptGuidelines: [
|
|
208
248
|
"Batch changes to the same file in one edit call.",
|
|
209
|
-
"
|
|
249
|
+
"Reuse prior anchors when their line number and content are unchanged. Re-read changed or shifted lines when no fresh anchor is available.",
|
|
210
250
|
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
211
251
|
],
|
|
212
252
|
parameters,
|
|
213
253
|
renderShell: "default" as const,
|
|
214
254
|
|
|
215
255
|
renderCall(args: EditParams, theme: any, context: any) {
|
|
216
|
-
|
|
217
|
-
// Stash the header for renderResult: the diff counts land after
|
|
218
|
-
// execution and are refreshed in place (renderResult's lastComponent
|
|
219
|
-
// is the result component, not this header)
|
|
220
|
-
if (context?.state) context.state.callText = text;
|
|
221
|
-
text.setText(editHeader(args, theme, context?.state?.diffCounts));
|
|
222
|
-
return text;
|
|
256
|
+
return renderMutationCall(args, theme, context, editHeader);
|
|
223
257
|
},
|
|
224
258
|
|
|
225
259
|
renderResult(result: any, options: any, theme: any, context: any) {
|
|
@@ -242,14 +276,7 @@ export function makeEditOverride(cwd: string, fusion?: ReturnType<typeof createA
|
|
|
242
276
|
(anchors) => { mutationAnchors = anchors; },
|
|
243
277
|
));
|
|
244
278
|
};
|
|
245
|
-
const finalizeMutation = (result: any, publishAnchors: boolean) => (
|
|
246
|
-
...result,
|
|
247
|
-
content: result.content.map((block: any, index: number) =>
|
|
248
|
-
index === 0 && block.type === "text"
|
|
249
|
-
? { ...block, text: `${block.text}${publishAnchors ? mutationAnchors : ""}` }
|
|
250
|
-
: block,
|
|
251
|
-
),
|
|
252
|
-
});
|
|
279
|
+
const finalizeMutation = (result: any, publishAnchors: boolean) => appendMutationAnchors(result, mutationAnchors, publishAnchors);
|
|
253
280
|
if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
|
|
254
281
|
return fusion({
|
|
255
282
|
toolCallId,
|
|
@@ -272,70 +299,34 @@ async function runHashline(
|
|
|
272
299
|
signal: AbortSignal | undefined,
|
|
273
300
|
onAnchors: (anchors: string) => void,
|
|
274
301
|
) {
|
|
275
|
-
const
|
|
302
|
+
const anchorFormatter = createAnchorFormatter();
|
|
303
|
+
const { shiftRadius } = getState().config;
|
|
276
304
|
|
|
277
|
-
|
|
278
|
-
let baseRevision: string;
|
|
279
|
-
try {
|
|
280
|
-
const currentBytes = await readFile(absPath);
|
|
281
|
-
baseRevision = byteRevision(currentBytes);
|
|
282
|
-
currentText = decodeEditableText(currentBytes);
|
|
283
|
-
} catch (e) {
|
|
284
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
285
|
-
throw new Error(`Error reading ${displayPath}: ${msg}`);
|
|
286
|
-
}
|
|
305
|
+
const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
|
|
287
306
|
// Check for cancel after read: if the user aborted, don't proceed to parse/apply; the file stays untouched
|
|
288
307
|
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before apply.`);
|
|
289
308
|
|
|
290
309
|
const translated = toCoreEdits(editOps);
|
|
291
310
|
if (!translated.ok) throw new Error(translated.error);
|
|
292
311
|
|
|
293
|
-
//
|
|
294
|
-
//
|
|
295
|
-
//
|
|
296
|
-
|
|
297
|
-
// the batch are collected (nothing written on any failure).
|
|
298
|
-
const result = applyEdits(currentText, translated.edits, hashLen, shiftRadius);
|
|
312
|
+
// Recovery reports checksum candidates from nearby lines, then the whole file
|
|
313
|
+
// if needed. Every failed anchor still rejects the batch; callers inspect
|
|
314
|
+
// candidates and resubmit with fresh anchors.
|
|
315
|
+
const result = applyEdits(currentText, translated.edits, anchorFormatter.hashLen, shiftRadius);
|
|
299
316
|
if (!result.ok) {
|
|
300
|
-
throw new Error(formatFailure(result.failure, { currentText,
|
|
317
|
+
throw new Error(formatFailure(result.failure, { currentText, anchors: anchorFormatter }));
|
|
301
318
|
}
|
|
302
319
|
|
|
303
320
|
// Check for cancel before write: if aborted, don't touch the disk; the file stays untouched
|
|
304
321
|
if (signal?.aborted) throw new Error(`Edit ${displayPath} aborted before write.`);
|
|
305
322
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
if (e instanceof FileMutationError) throw e;
|
|
314
|
-
throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
let details: EditToolDetails & MutationVersions & { publication: PublicationStatus; revision: string };
|
|
318
|
-
let anchors: string;
|
|
319
|
-
try {
|
|
320
|
-
// Diff and anchor generation happens after publication; preserve that state on failure.
|
|
321
|
-
const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
322
|
-
const newLf = result.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
323
|
-
const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
|
|
324
|
-
details = {
|
|
325
|
-
diff,
|
|
326
|
-
patch: generateUnifiedPatch(displayPath, oldLf, newLf),
|
|
327
|
-
firstChangedLine,
|
|
328
|
-
publication,
|
|
329
|
-
...versions,
|
|
330
|
-
revision: versions.publishedRevision,
|
|
323
|
+
const versions = await commitReplacement(absPath, displayPath, result.text, baseRevision, signal);
|
|
324
|
+
return postProcessMutation("edit", versions.publication, () => {
|
|
325
|
+
const details = generateMutationDetails(displayPath, currentText, result.text, versions, versions.publication);
|
|
326
|
+
onAnchors(formatUpdatedAnchors(currentText, result.text, result.touchedLines, result.contextLines, anchorFormatter));
|
|
327
|
+
return {
|
|
328
|
+
content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)${result.changed ? "" : ", no net change"}).` }],
|
|
329
|
+
details,
|
|
331
330
|
};
|
|
332
|
-
|
|
333
|
-
onAnchors(anchors);
|
|
334
|
-
} catch (error) {
|
|
335
|
-
throw new FileMutationError("post_process", publication, `file was published but edit result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
336
|
-
}
|
|
337
|
-
return {
|
|
338
|
-
content: [{ type: "text" as const, text: `Edited ${displayPath} (${translated.edits.length} op(s)).` }],
|
|
339
|
-
details,
|
|
340
|
-
};
|
|
331
|
+
});
|
|
341
332
|
}
|