pi-charset 0.1.4 → 0.1.6
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/CHANGELOG.md +64 -0
- package/CHANGELOG.zh-CN.md +64 -0
- package/CONTRIBUTING.md +33 -0
- package/CONTRIBUTING.zh-CN.md +33 -0
- package/README.md +35 -6
- package/README.zh-CN.md +35 -6
- package/docs/ACCEPTANCE.md +30 -2
- package/docs/COMPATIBILITY.md +6 -1
- package/docs/CONFIG-GUIDE.md +4 -1
- package/docs/DESIGN-REVIEW.md +54 -0
- package/docs/EDIT-ENGINE.md +46 -0
- package/docs/EDITING-PLAN.md +16 -0
- package/docs/MCP-AND-MULTI-AGENT.md +111 -0
- package/docs/MODEL-EVAL.md +92 -0
- package/docs/PROGRESS.md +311 -0
- package/docs/RELEASING.md +4 -2
- package/docs/zh-CN/ACCEPTANCE.md +30 -2
- package/docs/zh-CN/COMPATIBILITY.md +6 -1
- package/docs/zh-CN/CONFIG-GUIDE.md +4 -1
- package/docs/zh-CN/DESIGN-REVIEW.md +54 -0
- package/docs/zh-CN/EDIT-ENGINE.md +46 -0
- package/docs/zh-CN/EDITING-PLAN.md +415 -0
- package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +111 -0
- package/docs/zh-CN/MODEL-EVAL.md +92 -0
- package/docs/zh-CN/PROGRESS.md +311 -0
- package/docs/zh-CN/RELEASING.md +4 -2
- package/docs/zh-CN/editing-plan-architecture.png +0 -0
- package/examples/all-utf8.jsonc +1 -0
- package/examples/embedded-c.jsonc +1 -0
- package/examples/legacy-java-web.jsonc +1 -0
- package/examples/mixed-repo.jsonc +1 -0
- package/package.json +14 -2
- package/prompts/charset-setup.md +3 -3
- package/schema/pi-charset.schema.json +118 -0
- package/skills/charset-rules/SKILL.md +8 -2
- package/src/config.ts +524 -185
- package/src/edit/apply-patch-core.ts +275 -0
- package/src/edit/apply-patch.ts +78 -0
- package/src/edit/diagnostics.ts +48 -0
- package/src/edit/hashline.ts +438 -0
- package/src/edit/patch.ts +655 -0
- package/src/edit/paths.ts +42 -0
- package/src/edit/plan.ts +107 -0
- package/src/edit/tool.ts +451 -0
- package/src/edit-preview.ts +48 -277
- package/src/encoding/classify.ts +235 -65
- package/src/encoding/common-scripts.ts +66 -0
- package/src/encoding/converter.ts +114 -16
- package/src/encoding/fast-codec.ts +469 -0
- package/src/encoding/file-stamp.ts +55 -0
- package/src/encoding/line-endings.ts +66 -73
- package/src/encoding/mime.ts +12 -43
- package/src/encoding/stream-transcode.ts +135 -30
- package/src/grep-core.ts +687 -0
- package/src/grep.ts +25 -463
- package/src/index.ts +458 -49
- package/src/journal.ts +459 -0
- package/src/maintenance.ts +375 -0
- package/src/mcp/server.ts +651 -0
- package/src/operations.ts +759 -127
- package/src/read-view.ts +924 -0
- package/src/resolve.ts +113 -101
- package/src/scaffold.ts +9 -4
- package/src/shell-guard.ts +617 -0
- package/src/shell.ts +85 -33
- package/src/sysnote.ts +4 -6
- package/src/version.ts +1 -1
- package/tools/charset-core.mjs +251 -0
- package/tools/pi-charset-cli.mjs +369 -0
- package/tools/pi-charset-mcp.mjs +103 -0
- package/tools/scan-encoding.mjs +30 -28
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
// Commercial-grade patch parser and planner (pure, zero Pi SDK imports):
|
|
2
|
+
// Supports three formats seamlessly against one immutable source snapshot:
|
|
3
|
+
// 1. OpenAI Codex V4A `apply_patch` (`*** Begin Patch` / `*** Update|Add|Delete File` / `*** Move to`)
|
|
4
|
+
// 2. Standard Unified Diff (`diff --git` / `---` / `+++` / `@@ -a,b +c,d @@` / ``)
|
|
5
|
+
// 3. Aider `<<<<<<< SEARCH` / `=======` / `>>>>>>> REPLACE` fenced blocks
|
|
6
|
+
// Strict non-corrupting matching: exact anchored match first, then unique context match, never fuzzy guessing.
|
|
7
|
+
import { EditError, suggestLines } from "./diagnostics";
|
|
8
|
+
import { indexLines, planHashlineEdits, type HashlineOp, type LineSpan } from "./hashline";
|
|
9
|
+
import { assertNoMixedResult, assertUniformSource, assertValidText, planEdits, type EditRange, type EditReplacement, type PlannedText } from "./plan";
|
|
10
|
+
|
|
11
|
+
export interface PatchHunk {
|
|
12
|
+
/** Optional 1-based line number from unified diff `@@ -oldStart,oldCount +... @@`. */
|
|
13
|
+
readonly oldStart?: number;
|
|
14
|
+
/** Optional context anchor header text after `@@ ` (Codex or unified diff function header). */
|
|
15
|
+
readonly header?: string;
|
|
16
|
+
readonly oldLines: readonly string[];
|
|
17
|
+
readonly newLines: readonly string[];
|
|
18
|
+
readonly oldNoNewlineAtEof: boolean;
|
|
19
|
+
readonly newNoNewlineAtEof: boolean;
|
|
20
|
+
/** True when Codex `*** End of File` marker anchors the hunk to EOF. */
|
|
21
|
+
readonly atEndOfFile: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type MultiFilePatchOp =
|
|
25
|
+
| { readonly type: "add"; readonly path: string; readonly content: string }
|
|
26
|
+
| { readonly type: "delete"; readonly path: string }
|
|
27
|
+
| {
|
|
28
|
+
readonly type: "update";
|
|
29
|
+
readonly path: string;
|
|
30
|
+
readonly moveTo?: string;
|
|
31
|
+
readonly hunks: readonly PatchHunk[];
|
|
32
|
+
/** Populated when parsed from Aider multi-file SEARCH/REPLACE blocks. */
|
|
33
|
+
readonly searchReplace?: readonly EditReplacement[];
|
|
34
|
+
/** Populated when parsed from Codex-envelope `*** Hashline File: <path>` blocks. */
|
|
35
|
+
readonly hashlines?: readonly HashlineOp[];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const UNIFIED_HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s*(.*))?$/;
|
|
39
|
+
const CODEX_HUNK_RE = /^@@(?:\s+(.*))?$/;
|
|
40
|
+
const CODEX_BEGIN_RE = /^\*{3}\s*Begin Patch(?:\s*\*{3})?\s*$/;
|
|
41
|
+
const CODEX_END_RE = /^\*{3}\s*End Patch(?:\s*\*{3})?\s*$/;
|
|
42
|
+
const SEARCH_MARKER = /^<{7}\s*SEARCH\s*$/;
|
|
43
|
+
const SEP_MARKER = /^={7}\s*$/;
|
|
44
|
+
const REPLACE_MARKER = /^>{7}\s*REPLACE\s*$/;
|
|
45
|
+
|
|
46
|
+
/** Parse Aider-style `<<<<<<< SEARCH / ======= / >>>>>>> REPLACE` blocks into exact Search/Replace edits. */
|
|
47
|
+
export function parseSearchReplaceBlocks(text: string): EditReplacement[] | null {
|
|
48
|
+
const norm = text.replace(/\r\n/g, "\n");
|
|
49
|
+
const lines = norm.split("\n");
|
|
50
|
+
if (!lines.some((l) => SEARCH_MARKER.test(l))) return null;
|
|
51
|
+
|
|
52
|
+
const edits: EditReplacement[] = [];
|
|
53
|
+
let i = 0;
|
|
54
|
+
while (i < lines.length) {
|
|
55
|
+
if (!SEARCH_MARKER.test(lines[i])) {
|
|
56
|
+
if (lines[i].trim() !== "") {
|
|
57
|
+
throw new EditError("INVALID_INPUT", `Unexpected text outside SEARCH/REPLACE block at line ${i + 1}.`);
|
|
58
|
+
}
|
|
59
|
+
i++;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const startLine = i + 1;
|
|
63
|
+
i++;
|
|
64
|
+
const oldLines: string[] = [];
|
|
65
|
+
while (i < lines.length && !SEP_MARKER.test(lines[i])) oldLines.push(lines[i++]);
|
|
66
|
+
if (i >= lines.length) {
|
|
67
|
+
throw new EditError("INVALID_INPUT", `Unterminated SEARCH block starting at line ${startLine} (missing =======).`);
|
|
68
|
+
}
|
|
69
|
+
i++;
|
|
70
|
+
const newLines: string[] = [];
|
|
71
|
+
while (i < lines.length && !REPLACE_MARKER.test(lines[i])) newLines.push(lines[i++]);
|
|
72
|
+
if (i >= lines.length) {
|
|
73
|
+
throw new EditError("INVALID_INPUT", `Unterminated REPLACE block starting at line ${startLine} (missing >>>>>>> REPLACE).`);
|
|
74
|
+
}
|
|
75
|
+
i++;
|
|
76
|
+
edits.push({ oldText: oldLines.join("\n"), newText: newLines.join("\n") });
|
|
77
|
+
}
|
|
78
|
+
if (edits.length === 0) throw new EditError("INVALID_INPUT", "No SEARCH/REPLACE blocks found.");
|
|
79
|
+
return edits;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function parseHunkLines(lines: readonly string[], startIndex: number, stopAt: (line: string) => boolean): { hunks: PatchHunk[]; nextIndex: number } {
|
|
83
|
+
const hunks: PatchHunk[] = [];
|
|
84
|
+
let i = startIndex;
|
|
85
|
+
|
|
86
|
+
while (i < lines.length && !stopAt(lines[i])) {
|
|
87
|
+
const line = lines[i];
|
|
88
|
+
const uMatch = UNIFIED_HUNK_RE.exec(line);
|
|
89
|
+
const cMatch = !uMatch ? CODEX_HUNK_RE.exec(line) : null;
|
|
90
|
+
if (!uMatch && !cMatch) {
|
|
91
|
+
// Skip optional unified file headers (`diff --git`, `index`, `---`, `+++`) before first hunk.
|
|
92
|
+
if (hunks.length === 0 && /^(?:diff --git |index |--- |\+\+\+ |old mode |new mode |similarity |rename )/.test(line)) {
|
|
93
|
+
i++;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (line.trim() === "") {
|
|
97
|
+
i++;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
throw new EditError("INVALID_INPUT", `Expected hunk header "@@" at patch line ${i + 1}, got ${JSON.stringify(line.slice(0, 80))}.`);
|
|
101
|
+
}
|
|
102
|
+
const oldStart = uMatch ? Number(uMatch[1]) : undefined;
|
|
103
|
+
const oldCount = uMatch ? (uMatch[2] !== undefined ? Number(uMatch[2]) : 1) : undefined;
|
|
104
|
+
const newCount = uMatch ? (uMatch[4] !== undefined ? Number(uMatch[4]) : 1) : undefined;
|
|
105
|
+
const header = (uMatch ? uMatch[5] : cMatch?.[1])?.trim() || undefined;
|
|
106
|
+
i++;
|
|
107
|
+
|
|
108
|
+
const oldLines: string[] = [];
|
|
109
|
+
const newLines: string[] = [];
|
|
110
|
+
let oldNoNewlineAtEof = false;
|
|
111
|
+
let newNoNewlineAtEof = false;
|
|
112
|
+
let atEndOfFile = false;
|
|
113
|
+
let lastKind: " " | "-" | "+" | null = null;
|
|
114
|
+
|
|
115
|
+
while (i < lines.length && !stopAt(lines[i])) {
|
|
116
|
+
const cur = lines[i];
|
|
117
|
+
if (UNIFIED_HUNK_RE.test(cur) || CODEX_HUNK_RE.test(cur)) break;
|
|
118
|
+
if (cur === "*** End of File") {
|
|
119
|
+
atEndOfFile = true;
|
|
120
|
+
i++;
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
if (cur.startsWith("\")) {
|
|
124
|
+
if (lastKind === "-") oldNoNewlineAtEof = true;
|
|
125
|
+
else if (lastKind === "+") newNoNewlineAtEof = true;
|
|
126
|
+
else if (lastKind === " ") { oldNoNewlineAtEof = true; newNoNewlineAtEof = true; }
|
|
127
|
+
i++;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (cur.startsWith(" ")) {
|
|
131
|
+
const body = cur.slice(1);
|
|
132
|
+
oldLines.push(body);
|
|
133
|
+
newLines.push(body);
|
|
134
|
+
lastKind = " ";
|
|
135
|
+
i++;
|
|
136
|
+
} else if (cur.startsWith("-")) {
|
|
137
|
+
oldLines.push(cur.slice(1));
|
|
138
|
+
lastKind = "-";
|
|
139
|
+
i++;
|
|
140
|
+
} else if (cur.startsWith("+")) {
|
|
141
|
+
newLines.push(cur.slice(1));
|
|
142
|
+
lastKind = "+";
|
|
143
|
+
i++;
|
|
144
|
+
} else if (cur === "") {
|
|
145
|
+
const needsMoreUnified =
|
|
146
|
+
oldCount !== undefined && newCount !== undefined && (oldLines.length < oldCount || newLines.length < newCount);
|
|
147
|
+
// Trailing blank line at end of patch text or empty context line inside unified diff.
|
|
148
|
+
if (!needsMoreUnified && (i === lines.length - 1 || stopAt(lines[i + 1]) || UNIFIED_HUNK_RE.test(lines[i + 1]) || CODEX_HUNK_RE.test(lines[i + 1]))) {
|
|
149
|
+
i++;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
oldLines.push("");
|
|
153
|
+
newLines.push("");
|
|
154
|
+
lastKind = " ";
|
|
155
|
+
i++;
|
|
156
|
+
} else {
|
|
157
|
+
throw new EditError("INVALID_INPUT", `Invalid hunk body line ${i + 1} (must start with ' ', '-', or '+'): ${JSON.stringify(cur.slice(0, 80))}.`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (oldLines.length === 0 && newLines.length === 0) {
|
|
162
|
+
throw new EditError("INVALID_INPUT", "Empty patch hunk is not allowed.");
|
|
163
|
+
}
|
|
164
|
+
hunks.push({ oldStart, header, oldLines, newLines, oldNoNewlineAtEof, newNoNewlineAtEof, atEndOfFile });
|
|
165
|
+
}
|
|
166
|
+
return { hunks, nextIndex: i };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function stripGitPrefix(raw: string, prefix: "a/" | "b/"): string {
|
|
170
|
+
const clean = raw.replace(/\t.*$/, "").trim();
|
|
171
|
+
return clean.startsWith(prefix) ? clean.slice(prefix.length) : clean;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const HASHLINE_DIR_RE = /^@(replace|delete|insert_after|insert_before)\s+(\S+)$/;
|
|
175
|
+
|
|
176
|
+
/** Parse `@replace/@delete/@insert_after/@insert_before` directives inside a `*** Hashline File:` section. */
|
|
177
|
+
function parseHashlineBlock(
|
|
178
|
+
lines: readonly string[],
|
|
179
|
+
startIndex: number,
|
|
180
|
+
filePath: string,
|
|
181
|
+
stopAt: (line: string) => boolean,
|
|
182
|
+
): { ops: HashlineOp[]; nextIndex: number } {
|
|
183
|
+
const ops: HashlineOp[] = [];
|
|
184
|
+
let i = startIndex;
|
|
185
|
+
while (i < lines.length && !stopAt(lines[i])) {
|
|
186
|
+
if (lines[i].trim() === "") {
|
|
187
|
+
i++;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const m = HASHLINE_DIR_RE.exec(lines[i].trim());
|
|
191
|
+
if (!m) {
|
|
192
|
+
throw new EditError(
|
|
193
|
+
"INVALID_INPUT",
|
|
194
|
+
`Hashline File "${filePath}" line ${i + 1}: expected "@replace|@delete|@insert_after|@insert_before <anchor>", got ${JSON.stringify(lines[i].slice(0, 80))}.`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
const kind = m[1] as HashlineOp["op"];
|
|
198
|
+
const refSpec = m[2];
|
|
199
|
+
const dirLine = i + 1;
|
|
200
|
+
i++;
|
|
201
|
+
const body: string[] = [];
|
|
202
|
+
while (i < lines.length && !stopAt(lines[i]) && !HASHLINE_DIR_RE.test(lines[i].trim())) {
|
|
203
|
+
body.push(lines[i]);
|
|
204
|
+
i++;
|
|
205
|
+
}
|
|
206
|
+
if (kind === "delete") {
|
|
207
|
+
if (body.some((l) => l.trim() !== "")) {
|
|
208
|
+
throw new EditError("INVALID_INPUT", `Hashline File "${filePath}" @delete at line ${dirLine} must not have body lines.`);
|
|
209
|
+
}
|
|
210
|
+
const [start, end] = refSpec.includes("..") ? refSpec.split("..", 2) : [refSpec, undefined];
|
|
211
|
+
ops.push(end ? { op: "delete", start, end } : { op: "delete", start });
|
|
212
|
+
} else if (kind === "replace") {
|
|
213
|
+
const [start, end] = refSpec.includes("..") ? refSpec.split("..", 2) : [refSpec, undefined];
|
|
214
|
+
const content = body.join("\n");
|
|
215
|
+
ops.push(end ? { op: "replace", start, end, content } : { op: "replace", start, content });
|
|
216
|
+
} else {
|
|
217
|
+
if (body.length === 0) {
|
|
218
|
+
throw new EditError("INVALID_INPUT", `Hashline File "${filePath}" @${kind} at line ${dirLine} requires at least one content line.`);
|
|
219
|
+
}
|
|
220
|
+
ops.push({ op: kind, anchor: refSpec, content: body.join("\n") });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return { ops, nextIndex: i };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Unwrap a single outer Markdown code fence (e.g. ```patch ... ``` or ```diff ... ```) emitted by some models. */
|
|
227
|
+
function unwrapOuterFence(text: string): string {
|
|
228
|
+
const norm = text.replace(/\r\n/g, "\n");
|
|
229
|
+
const lines = norm.split("\n");
|
|
230
|
+
let first = 0;
|
|
231
|
+
while (first < lines.length && lines[first].trim() === "") first++;
|
|
232
|
+
let last = lines.length - 1;
|
|
233
|
+
while (last > first && lines[last].trim() === "") last--;
|
|
234
|
+
if (last > first && /^```[A-Za-z0-9_-]*\s*$/.test(lines[first].trim()) && lines[last].trim() === "```") {
|
|
235
|
+
// Only unwrap when no intermediate fence closes before `last` (preserves multi-block Aider fenced responses).
|
|
236
|
+
const inner = lines.slice(first + 1, last);
|
|
237
|
+
if (!inner.some((l) => l.trim().startsWith("```"))) {
|
|
238
|
+
return inner.join("\n");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return norm;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Parse a multi-file patch in Codex `*** Begin Patch` (Update/Hashline/Add/Delete/Move), Aider SEARCH/REPLACE, or unified diff format. */
|
|
245
|
+
export function parseMultiFilePatch(patchText: string): MultiFilePatchOp[] {
|
|
246
|
+
assertValidText(patchText, "Patch", true);
|
|
247
|
+
if (!patchText.trim()) throw new EditError("INVALID_INPUT", "Patch must be nonempty.");
|
|
248
|
+
const lines = unwrapOuterFence(patchText).split("\n");
|
|
249
|
+
if (lines[lines.length - 1] === "") lines.pop();
|
|
250
|
+
|
|
251
|
+
const ops: MultiFilePatchOp[] = [];
|
|
252
|
+
const isCodexHeader = (l: string) =>
|
|
253
|
+
CODEX_END_RE.test(l) ||
|
|
254
|
+
l.startsWith("*** Update File: ") ||
|
|
255
|
+
l.startsWith("*** Hashline File: ") ||
|
|
256
|
+
l.startsWith("*** Add File: ") ||
|
|
257
|
+
l.startsWith("*** Delete File: ");
|
|
258
|
+
|
|
259
|
+
// 1. Codex V4A format (`*** Begin Patch` / `*** Begin Patch ***` ... `*** End Patch`)
|
|
260
|
+
const beginIdx = lines.findIndex((l) => l.trim() !== "");
|
|
261
|
+
if (beginIdx !== -1 && CODEX_BEGIN_RE.test(lines[beginIdx])) {
|
|
262
|
+
let i = beginIdx + 1;
|
|
263
|
+
let sawEnd = false;
|
|
264
|
+
while (i < lines.length) {
|
|
265
|
+
const l = lines[i];
|
|
266
|
+
if (CODEX_END_RE.test(l)) {
|
|
267
|
+
sawEnd = true;
|
|
268
|
+
i++;
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
if (l.trim() === "") {
|
|
272
|
+
i++;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (l.startsWith("*** Add File: ")) {
|
|
276
|
+
const filePath = l.slice("*** Add File: ".length).trim();
|
|
277
|
+
if (!filePath) throw new EditError("INVALID_INPUT", `Missing path in "${l}".`);
|
|
278
|
+
i++;
|
|
279
|
+
const body: string[] = [];
|
|
280
|
+
let noTrailingNl = false;
|
|
281
|
+
while (i < lines.length && !isCodexHeader(lines[i])) {
|
|
282
|
+
if (lines[i] === "*** End of File" || lines[i].startsWith("\")) {
|
|
283
|
+
noTrailingNl = true;
|
|
284
|
+
i++;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
if (!lines[i].startsWith("+")) {
|
|
288
|
+
throw new EditError("INVALID_INPUT", `Add File "${filePath}" line ${i + 1} must start with '+'.`);
|
|
289
|
+
}
|
|
290
|
+
body.push(lines[i].slice(1));
|
|
291
|
+
i++;
|
|
292
|
+
}
|
|
293
|
+
const content = body.length === 0 ? "" : body.join("\n") + (noTrailingNl ? "" : "\n");
|
|
294
|
+
ops.push({ type: "add", path: filePath, content });
|
|
295
|
+
} else if (l.startsWith("*** Delete File: ")) {
|
|
296
|
+
const filePath = l.slice("*** Delete File: ".length).trim();
|
|
297
|
+
if (!filePath) throw new EditError("INVALID_INPUT", `Missing path in "${l}".`);
|
|
298
|
+
ops.push({ type: "delete", path: filePath });
|
|
299
|
+
i++;
|
|
300
|
+
} else if (l.startsWith("*** Hashline File: ")) {
|
|
301
|
+
const filePath = l.slice("*** Hashline File: ".length).trim();
|
|
302
|
+
if (!filePath) throw new EditError("INVALID_INPUT", `Missing path in "${l}".`);
|
|
303
|
+
i++;
|
|
304
|
+
let moveTo: string | undefined;
|
|
305
|
+
if (i < lines.length && lines[i].startsWith("*** Move to: ")) {
|
|
306
|
+
moveTo = lines[i].slice("*** Move to: ".length).trim();
|
|
307
|
+
if (!moveTo) throw new EditError("INVALID_INPUT", `Missing destination in "${lines[i]}".`);
|
|
308
|
+
i++;
|
|
309
|
+
}
|
|
310
|
+
const { ops: hashOps, nextIndex } = parseHashlineBlock(lines, i, filePath, isCodexHeader);
|
|
311
|
+
if (hashOps.length === 0 && !moveTo) {
|
|
312
|
+
throw new EditError("INVALID_INPUT", `Hashline File "${filePath}" has no directives and no Move to target.`);
|
|
313
|
+
}
|
|
314
|
+
ops.push({ type: "update", path: filePath, moveTo, hunks: [], hashlines: hashOps });
|
|
315
|
+
i = nextIndex;
|
|
316
|
+
} else if (l.startsWith("*** Update File: ")) {
|
|
317
|
+
const filePath = l.slice("*** Update File: ".length).trim();
|
|
318
|
+
if (!filePath) throw new EditError("INVALID_INPUT", `Missing path in "${l}".`);
|
|
319
|
+
i++;
|
|
320
|
+
let moveTo: string | undefined;
|
|
321
|
+
if (i < lines.length && lines[i].startsWith("*** Move to: ")) {
|
|
322
|
+
moveTo = lines[i].slice("*** Move to: ".length).trim();
|
|
323
|
+
if (!moveTo) throw new EditError("INVALID_INPUT", `Missing destination in "${lines[i]}".`);
|
|
324
|
+
i++;
|
|
325
|
+
}
|
|
326
|
+
const { hunks, nextIndex } = parseHunkLines(lines, i, isCodexHeader);
|
|
327
|
+
if (hunks.length === 0 && !moveTo) {
|
|
328
|
+
throw new EditError("INVALID_INPUT", `Update File "${filePath}" has no hunks and no Move to target.`);
|
|
329
|
+
}
|
|
330
|
+
ops.push({ type: "update", path: filePath, moveTo, hunks });
|
|
331
|
+
i = nextIndex;
|
|
332
|
+
} else {
|
|
333
|
+
throw new EditError("INVALID_INPUT", `Unexpected Codex patch directive at line ${i + 1}: ${JSON.stringify(l.slice(0, 80))}.`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (!sawEnd) throw new EditError("INVALID_INPUT", 'Missing "*** End Patch" terminator.');
|
|
337
|
+
if (ops.length === 0) throw new EditError("INVALID_INPUT", "Patch contains no file operations.");
|
|
338
|
+
return ops;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 2. Aider multi-file SEARCH/REPLACE blocks (`path/to/file\n<<<<<<< SEARCH\n...\n=======\n...\n>>>>>>> REPLACE`)
|
|
342
|
+
if (lines.some((l) => SEARCH_MARKER.test(l))) {
|
|
343
|
+
const byFile = new Map<string, EditReplacement[]>();
|
|
344
|
+
const order: string[] = [];
|
|
345
|
+
let i = 0;
|
|
346
|
+
while (i < lines.length) {
|
|
347
|
+
while (i < lines.length && lines[i].trim() === "") i++;
|
|
348
|
+
if (i >= lines.length) break;
|
|
349
|
+
// Optional markdown code fence around Aider blocks (` ``` ` / ` ```c `).
|
|
350
|
+
if (lines[i].startsWith("```")) { i++; continue; }
|
|
351
|
+
const rawFile = lines[i].trim().replace(/^`|`$/g, "");
|
|
352
|
+
if (SEARCH_MARKER.test(rawFile)) {
|
|
353
|
+
throw new EditError("INVALID_INPUT", `Missing file path header before SEARCH block at line ${i + 1}.`);
|
|
354
|
+
}
|
|
355
|
+
i++;
|
|
356
|
+
while (i < lines.length && (lines[i].trim() === "" || lines[i].startsWith("```"))) i++;
|
|
357
|
+
if (i >= lines.length || !SEARCH_MARKER.test(lines[i])) {
|
|
358
|
+
throw new EditError("INVALID_INPUT", `Expected "<<<<<<< SEARCH" after path "${rawFile}" at line ${i + 1}.`);
|
|
359
|
+
}
|
|
360
|
+
const startLine = i + 1;
|
|
361
|
+
i++;
|
|
362
|
+
const oldLines: string[] = [];
|
|
363
|
+
while (i < lines.length && !SEP_MARKER.test(lines[i])) oldLines.push(lines[i++]);
|
|
364
|
+
if (i >= lines.length) throw new EditError("INVALID_INPUT", `Unterminated SEARCH block for "${rawFile}" at line ${startLine}.`);
|
|
365
|
+
i++;
|
|
366
|
+
const newLines: string[] = [];
|
|
367
|
+
while (i < lines.length && !REPLACE_MARKER.test(lines[i])) newLines.push(lines[i++]);
|
|
368
|
+
if (i >= lines.length) throw new EditError("INVALID_INPUT", `Unterminated REPLACE block for "${rawFile}" at line ${startLine}.`);
|
|
369
|
+
i++;
|
|
370
|
+
if (i < lines.length && lines[i].startsWith("```")) i++;
|
|
371
|
+
let list = byFile.get(rawFile);
|
|
372
|
+
if (!list) {
|
|
373
|
+
list = [];
|
|
374
|
+
byFile.set(rawFile, list);
|
|
375
|
+
order.push(rawFile);
|
|
376
|
+
}
|
|
377
|
+
list.push({ oldText: oldLines.join("\n"), newText: newLines.join("\n") });
|
|
378
|
+
}
|
|
379
|
+
if (order.length === 0) throw new EditError("INVALID_INPUT", "Patch contains no file operations.");
|
|
380
|
+
return order.map((filePath) => ({
|
|
381
|
+
type: "update" as const,
|
|
382
|
+
path: filePath,
|
|
383
|
+
hunks: [],
|
|
384
|
+
searchReplace: byFile.get(filePath)!,
|
|
385
|
+
}));
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// 3. Standard Unified Multi-File Diff (`diff --git` / `--- ...` / `+++ ...`)
|
|
389
|
+
const isUnifiedFileStart = (l: string) => l.startsWith("diff --git ") || l.startsWith("--- ");
|
|
390
|
+
let i = 0;
|
|
391
|
+
while (i < lines.length) {
|
|
392
|
+
if (lines[i].trim() === "") { i++; continue; }
|
|
393
|
+
if (!isUnifiedFileStart(lines[i])) {
|
|
394
|
+
throw new EditError("INVALID_INPUT", `Expected "diff --git" or "--- " file header at line ${i + 1}.`);
|
|
395
|
+
}
|
|
396
|
+
let oldPath: string | null = null;
|
|
397
|
+
let newPath: string | null = null;
|
|
398
|
+
let renameFrom: string | undefined;
|
|
399
|
+
let renameTo: string | undefined;
|
|
400
|
+
if (lines[i].startsWith("diff --git ")) i++;
|
|
401
|
+
while (i < lines.length && !lines[i].startsWith("@@") && !lines[i].startsWith("diff --git ")) {
|
|
402
|
+
const l = lines[i];
|
|
403
|
+
if (l.startsWith("--- ")) oldPath = l.slice(4).replace(/\t.*$/, "").trim();
|
|
404
|
+
else if (l.startsWith("+++ ")) newPath = l.slice(4).replace(/\t.*$/, "").trim();
|
|
405
|
+
else if (l.startsWith("rename from ")) renameFrom = l.slice(12).trim();
|
|
406
|
+
else if (l.startsWith("rename to ")) renameTo = l.slice(10).trim();
|
|
407
|
+
i++;
|
|
408
|
+
if (oldPath !== null && newPath !== null) break;
|
|
409
|
+
}
|
|
410
|
+
const { hunks, nextIndex } = parseHunkLines(lines, i, isUnifiedFileStart);
|
|
411
|
+
i = nextIndex;
|
|
412
|
+
|
|
413
|
+
const isAdd = oldPath === "/dev/null" && newPath !== null && newPath !== "/dev/null";
|
|
414
|
+
const isDelete = newPath === "/dev/null" && oldPath !== null && oldPath !== "/dev/null";
|
|
415
|
+
if (isAdd) {
|
|
416
|
+
const added: string[] = [];
|
|
417
|
+
let noNl = false;
|
|
418
|
+
for (const h of hunks) {
|
|
419
|
+
if (h.oldLines.length > 0) throw new EditError("INVALID_INPUT", `Add file patch for ${newPath} contains old lines.`);
|
|
420
|
+
added.push(...h.newLines);
|
|
421
|
+
if (h.newNoNewlineAtEof) noNl = true;
|
|
422
|
+
}
|
|
423
|
+
const p = stripGitPrefix(newPath!, "b/");
|
|
424
|
+
ops.push({ type: "add", path: p, content: added.length ? added.join("\n") + (noNl ? "" : "\n") : "" });
|
|
425
|
+
} else if (isDelete) {
|
|
426
|
+
ops.push({ type: "delete", path: stripGitPrefix(oldPath!, "a/") });
|
|
427
|
+
} else {
|
|
428
|
+
const rawOld = oldPath ?? renameFrom;
|
|
429
|
+
const rawNew = newPath ?? renameTo;
|
|
430
|
+
if (!rawOld || !rawNew) throw new EditError("INVALID_INPUT", "Unified diff section is missing ---/+++ file headers.");
|
|
431
|
+
const hasGitPair = (rawOld.startsWith("a/") && rawNew.startsWith("b/"));
|
|
432
|
+
const src = hasGitPair ? stripGitPrefix(rawOld, "a/") : rawOld;
|
|
433
|
+
const dst = hasGitPair ? stripGitPrefix(rawNew, "b/") : rawNew;
|
|
434
|
+
ops.push({ type: "update", path: src, moveTo: dst !== src ? dst : undefined, hunks });
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (ops.length === 0) throw new EditError("INVALID_INPUT", "Patch contains no file operations.");
|
|
438
|
+
return ops;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function linesMatchAt(source: string, spans: readonly LineSpan[], at: number, expected: readonly string[]): boolean {
|
|
442
|
+
if (at < 0 || at + expected.length > spans.length) return false;
|
|
443
|
+
for (let k = 0; k < expected.length; k++) {
|
|
444
|
+
const s = spans[at + k];
|
|
445
|
+
if (source.slice(s.start, s.bodyEnd) !== expected[k]) return false;
|
|
446
|
+
}
|
|
447
|
+
return true;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Plan a parsed list of hunks against one immutable source snapshot `before`. */
|
|
451
|
+
export function planHunks(before: string, hunks: readonly PatchHunk[]): PlannedText {
|
|
452
|
+
const kind = assertUniformSource(before);
|
|
453
|
+
if (hunks.length === 0) return { before, after: before, ranges: [], changed: false };
|
|
454
|
+
|
|
455
|
+
const spans = indexLines(before);
|
|
456
|
+
const eol = kind === "CRLF" ? "\r\n" : "\n";
|
|
457
|
+
|
|
458
|
+
interface MatchedHunk {
|
|
459
|
+
readonly index: number;
|
|
460
|
+
readonly lineStart: number; // 0-based inclusive index into spans
|
|
461
|
+
readonly lineEnd: number; // 0-based exclusive index into spans
|
|
462
|
+
readonly hunk: PatchHunk;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const matched: MatchedHunk[] = [];
|
|
466
|
+
|
|
467
|
+
for (let hi = 0; hi < hunks.length; hi++) {
|
|
468
|
+
const h = hunks[hi];
|
|
469
|
+
for (const l of h.newLines) {
|
|
470
|
+
assertValidText(l, `Patch hunk #${hi + 1}`);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Pure insertion into an empty file (`@@ -0,0 +1,N @@`).
|
|
474
|
+
if (h.oldLines.length === 0) {
|
|
475
|
+
if (spans.length === 0 || h.oldStart === 0) {
|
|
476
|
+
matched.push({ index: hi, lineStart: 0, lineEnd: 0, hunk: h });
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (h.oldStart !== undefined && h.oldStart >= 1 && h.oldStart <= spans.length) {
|
|
480
|
+
matched.push({ index: hi, lineStart: h.oldStart, lineEnd: h.oldStart, hunk: h });
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
throw new EditError("INVALID_INPUT", `Patch hunk #${hi + 1} has no context lines and no valid insertion line.`);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// 1. Anchored EOF match (`*** End of File`).
|
|
487
|
+
if (h.atEndOfFile) {
|
|
488
|
+
const at = spans.length - h.oldLines.length;
|
|
489
|
+
if (!linesMatchAt(before, spans, at, h.oldLines)) {
|
|
490
|
+
throw new EditError(
|
|
491
|
+
"NOT_FOUND",
|
|
492
|
+
`Patch hunk #${hi + 1} marked End of File did not match the end of the file.` +
|
|
493
|
+
suggestLines(before, h.oldLines.join("\n")),
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
matched.push({ index: hi, lineStart: at, lineEnd: spans.length, hunk: h });
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// 2. Exact unified-diff anchored line number match (`@@ -oldStart,... @@`).
|
|
501
|
+
if (h.oldStart !== undefined && h.oldStart >= 1) {
|
|
502
|
+
const anchored = h.oldStart - 1;
|
|
503
|
+
if (linesMatchAt(before, spans, anchored, h.oldLines)) {
|
|
504
|
+
matched.push({ index: hi, lineStart: anchored, lineEnd: anchored + h.oldLines.length, hunk: h });
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// 3. Scope-narrowed or whole-file exact unique search (handles Codex `@@` and shifted unified hunks).
|
|
510
|
+
const allHits: number[] = [];
|
|
511
|
+
for (let pos = 0; pos <= spans.length - h.oldLines.length; pos++) {
|
|
512
|
+
if (linesMatchAt(before, spans, pos, h.oldLines)) allHits.push(pos);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
let chosen = allHits;
|
|
516
|
+
if (chosen.length > 1 && h.header) {
|
|
517
|
+
const headerLines: number[] = [];
|
|
518
|
+
for (let pos = 0; pos < spans.length; pos++) {
|
|
519
|
+
if (before.slice(spans[pos].start, spans[pos].bodyEnd).includes(h.header)) headerLines.push(pos);
|
|
520
|
+
}
|
|
521
|
+
if (headerLines.length === 1) {
|
|
522
|
+
const hPos = headerLines[0];
|
|
523
|
+
// Prefer an immediate match right after the unique @@ header line (Codex V4A convention),
|
|
524
|
+
// or a unique match anywhere after the header.
|
|
525
|
+
if (chosen.includes(hPos + 1)) {
|
|
526
|
+
chosen = [hPos + 1];
|
|
527
|
+
} else {
|
|
528
|
+
const afterHeader = chosen.filter((pos) => pos >= hPos);
|
|
529
|
+
if (afterHeader.length === 1) chosen = afterHeader;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
if (chosen.length === 0) {
|
|
535
|
+
throw new EditError(
|
|
536
|
+
"NOT_FOUND",
|
|
537
|
+
`Patch hunk #${hi + 1} could not be located in the file.` + suggestLines(before, h.oldLines.join("\n")),
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
if (chosen.length > 1) {
|
|
541
|
+
const lineNums = chosen.slice(0, 6).map((p) => p + 1).join(", ");
|
|
542
|
+
throw new EditError(
|
|
543
|
+
"AMBIGUOUS_MATCH",
|
|
544
|
+
`Patch hunk #${hi + 1} matched ${chosen.length} locations (lines ${lineNums}). Add more context lines.`,
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
const at = chosen[0];
|
|
548
|
+
matched.push({ index: hi, lineStart: at, lineEnd: at + h.oldLines.length, hunk: h });
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
matched.sort((a, b) => a.lineStart - b.lineStart || a.lineEnd - b.lineEnd || a.index - b.index);
|
|
552
|
+
for (let i = 1; i < matched.length; i++) {
|
|
553
|
+
const prev = matched[i - 1];
|
|
554
|
+
const cur = matched[i];
|
|
555
|
+
if (prev.lineEnd > cur.lineStart || (prev.lineStart === prev.lineEnd && cur.lineStart === cur.lineEnd && prev.lineStart === cur.lineStart)) {
|
|
556
|
+
throw new EditError(
|
|
557
|
+
"OVERLAPPING_EDITS",
|
|
558
|
+
`Patch hunks #${prev.index + 1} and #${cur.index + 1} overlap in the original file.`,
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const ranges: EditRange[] = [];
|
|
564
|
+
const parts: string[] = [];
|
|
565
|
+
let charPos = 0;
|
|
566
|
+
|
|
567
|
+
for (const m of matched) {
|
|
568
|
+
const { hunk, lineStart, lineEnd } = m;
|
|
569
|
+
let start: number;
|
|
570
|
+
let end: number;
|
|
571
|
+
let text: string;
|
|
572
|
+
|
|
573
|
+
if (lineStart === lineEnd) {
|
|
574
|
+
// Pure insertion at lineStart (empty file or explicit `@@ -L,0 +... @@`).
|
|
575
|
+
start = lineStart < spans.length ? spans[lineStart].start : before.length;
|
|
576
|
+
end = start;
|
|
577
|
+
const needsLeadEol = lineStart === spans.length && spans.length > 0 && !spans[spans.length - 1].hasEol;
|
|
578
|
+
const trail = hunk.newNoNewlineAtEof && lineStart === spans.length ? "" : needsLeadEol ? "" : eol;
|
|
579
|
+
text = hunk.newLines.length ? (needsLeadEol ? eol : "") + hunk.newLines.join(eol) + trail : "";
|
|
580
|
+
} else {
|
|
581
|
+
const firstSpan = spans[lineStart];
|
|
582
|
+
const lastSpan = spans[lineEnd - 1];
|
|
583
|
+
const touchesEof = lineEnd === spans.length;
|
|
584
|
+
|
|
585
|
+
if (hunk.newLines.length === 0) {
|
|
586
|
+
// Pure deletion of lines [lineStart..lineEnd).
|
|
587
|
+
start = !lastSpan.hasEol && lineStart > 0 ? spans[lineStart - 1].bodyEnd : firstSpan.start;
|
|
588
|
+
end = lastSpan.fullEnd;
|
|
589
|
+
text = "";
|
|
590
|
+
} else {
|
|
591
|
+
start = firstSpan.start;
|
|
592
|
+
end = lastSpan.fullEnd;
|
|
593
|
+
let wantsTrail: boolean;
|
|
594
|
+
if (!touchesEof) {
|
|
595
|
+
wantsTrail = true;
|
|
596
|
+
} else if (hunk.newNoNewlineAtEof) {
|
|
597
|
+
wantsTrail = false;
|
|
598
|
+
} else if (hunk.oldNoNewlineAtEof) {
|
|
599
|
+
// Old lacked trailing newline, new did not mark No-newline -> adds trailing EOL.
|
|
600
|
+
wantsTrail = true;
|
|
601
|
+
} else {
|
|
602
|
+
wantsTrail = lastSpan.hasEol;
|
|
603
|
+
}
|
|
604
|
+
text = hunk.newLines.join(eol) + (wantsTrail ? eol : "");
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (start < charPos) {
|
|
609
|
+
throw new EditError("OVERLAPPING_EDITS", `Patch hunk #${m.index + 1} overlaps a preceding hunk at the line boundary.`);
|
|
610
|
+
}
|
|
611
|
+
parts.push(before.slice(charPos, start), text);
|
|
612
|
+
ranges.push({ index: m.index, start, end, text });
|
|
613
|
+
charPos = end;
|
|
614
|
+
}
|
|
615
|
+
parts.push(before.slice(charPos));
|
|
616
|
+
const after = parts.join("");
|
|
617
|
+
assertNoMixedResult(after, kind, "Patch");
|
|
618
|
+
return { before, after, ranges, changed: after !== before };
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Plan a single-file patch string in any of the three formats:
|
|
623
|
+
* Aider SEARCH/REPLACE blocks, Codex single-file patch, or standard unified diff / bare hunks.
|
|
624
|
+
*/
|
|
625
|
+
export function planPatchEdits(before: string, patchText: string): PlannedText {
|
|
626
|
+
assertValidText(patchText, "patch", true);
|
|
627
|
+
if (!patchText.trim()) throw new EditError("INVALID_INPUT", "patch must be nonempty.");
|
|
628
|
+
const unwrapped = unwrapOuterFence(patchText);
|
|
629
|
+
|
|
630
|
+
// 1. Aider SEARCH/REPLACE blocks
|
|
631
|
+
const srBlocks = parseSearchReplaceBlocks(unwrapped);
|
|
632
|
+
if (srBlocks) return planEdits(before, srBlocks);
|
|
633
|
+
|
|
634
|
+
// 2. Codex single-file `*** Begin Patch` wrapper
|
|
635
|
+
const trimmed = unwrapped.trimStart();
|
|
636
|
+
if (CODEX_BEGIN_RE.test(trimmed.split(/\r?\n/, 1)[0] ?? "")) {
|
|
637
|
+
const ops = parseMultiFilePatch(unwrapped);
|
|
638
|
+
if (ops.length !== 1 || ops[0].type !== "update") {
|
|
639
|
+
throw new EditError("INVALID_INPUT", "Single-file edit patch must contain exactly one Update File entry; use apply_patch for multi-file patches.");
|
|
640
|
+
}
|
|
641
|
+
if (ops[0].moveTo) {
|
|
642
|
+
throw new EditError("INVALID_INPUT", "Single-file edit does not support '*** Move to:'; use apply_patch instead.");
|
|
643
|
+
}
|
|
644
|
+
return ops[0].hashlines ? planHashlineEdits(before, ops[0].hashlines) : planHunks(before, ops[0].hunks);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// 3. Standard unified diff or bare `@@` hunks
|
|
648
|
+
const lines = unwrapped.split("\n");
|
|
649
|
+
if (lines[lines.length - 1] === "") lines.pop();
|
|
650
|
+
const { hunks } = parseHunkLines(lines, 0, () => false);
|
|
651
|
+
if (hunks.length === 0) {
|
|
652
|
+
throw new EditError("INVALID_INPUT", "Patch contains no hunks.");
|
|
653
|
+
}
|
|
654
|
+
return planHunks(before, hunks);
|
|
655
|
+
}
|