pi-charset 0.1.4 → 0.1.5
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 +50 -0
- package/CHANGELOG.zh-CN.md +50 -0
- package/CONTRIBUTING.md +33 -0
- package/CONTRIBUTING.zh-CN.md +33 -0
- package/README.md +32 -6
- package/README.zh-CN.md +32 -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/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/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 +12 -2
- package/prompts/charset-setup.md +3 -3
- package/schema/pi-charset.schema.json +112 -0
- package/skills/charset-rules/SKILL.md +8 -2
- package/src/config.ts +444 -181
- package/src/edit/apply-patch.ts +388 -0
- package/src/edit/diagnostics.ts +45 -0
- package/src/edit/hashline.ts +438 -0
- package/src/edit/patch.ts +655 -0
- package/src/edit/plan.ts +107 -0
- package/src/edit/tool.ts +488 -0
- package/src/edit-preview.ts +48 -277
- package/src/encoding/classify.ts +222 -64
- package/src/encoding/common-scripts.ts +66 -0
- package/src/encoding/converter.ts +111 -15
- 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.ts +433 -170
- package/src/index.ts +458 -49
- package/src/journal.ts +459 -0
- package/src/maintenance.ts +375 -0
- package/src/operations.ts +757 -127
- package/src/read-view.ts +924 -0
- package/src/resolve.ts +112 -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 +240 -0
- package/tools/pi-charset-cli.mjs +221 -0
- package/tools/scan-encoding.mjs +30 -28
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// Multi-file encoding-safe `apply_patch` tool (Codex V4A `*** Begin Patch` and standard unified multi-file diff).
|
|
2
|
+
// Enforces all-or-nothing pre-flight validation before any disk mutation and acquires path locks in sorted order.
|
|
3
|
+
import { lstat, mkdir, readFile, unlink } from "node:fs/promises";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { Type, type Static } from "typebox";
|
|
6
|
+
import { Box, Spacer, Text } from "@earendil-works/pi-tui";
|
|
7
|
+
import { renderDiff, type AgentToolResult, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import {
|
|
9
|
+
afterWrite,
|
|
10
|
+
atomicReplace,
|
|
11
|
+
canonicalKey,
|
|
12
|
+
checkEditAbort,
|
|
13
|
+
commitPlanLocked,
|
|
14
|
+
loadSnapshot,
|
|
15
|
+
prepareEditWithPlan,
|
|
16
|
+
prepareNewFileWrite,
|
|
17
|
+
verifyWritten,
|
|
18
|
+
withPathLocks,
|
|
19
|
+
type FileSnapshot,
|
|
20
|
+
type PreparedEdit,
|
|
21
|
+
type ReadScope,
|
|
22
|
+
} from "../operations";
|
|
23
|
+
import { allocateBatchId, autoCommitBatch, recordWrite } from "../journal";
|
|
24
|
+
import type { ResolvedConfig } from "../config";
|
|
25
|
+
import { drainEncodingNotes, notesToSuffix, pushEncodingNote } from "../notify";
|
|
26
|
+
import { EditError } from "./diagnostics";
|
|
27
|
+
import { formatUpdatedHashlines, planHashlineEdits } from "./hashline";
|
|
28
|
+
import { planEdits } from "./plan";
|
|
29
|
+
import { parseMultiFilePatch, planHunks } from "./patch";
|
|
30
|
+
import { buildEditDiff, resolveEditPath } from "./tool";
|
|
31
|
+
|
|
32
|
+
export const applyPatchSchema = Type.Object({
|
|
33
|
+
patch: Type.String(),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export type ApplyPatchInput = Static<typeof applyPatchSchema>;
|
|
37
|
+
|
|
38
|
+
export interface ApplyPatchFileResult {
|
|
39
|
+
readonly action: "added" | "updated" | "unchanged" | "deleted" | "moved";
|
|
40
|
+
readonly path: string;
|
|
41
|
+
readonly movedTo?: string;
|
|
42
|
+
readonly diff?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ApplyPatchDetails {
|
|
46
|
+
readonly files: readonly ApplyPatchFileResult[];
|
|
47
|
+
readonly batchId?: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type PreparedPatchOp =
|
|
51
|
+
| {
|
|
52
|
+
readonly kind: "add";
|
|
53
|
+
readonly displayPath: string;
|
|
54
|
+
readonly absPath: string;
|
|
55
|
+
readonly key: string;
|
|
56
|
+
readonly prepared: Awaited<ReturnType<typeof prepareNewFileWrite>>;
|
|
57
|
+
}
|
|
58
|
+
| {
|
|
59
|
+
readonly kind: "delete";
|
|
60
|
+
readonly displayPath: string;
|
|
61
|
+
readonly absPath: string;
|
|
62
|
+
readonly snapshot: FileSnapshot;
|
|
63
|
+
}
|
|
64
|
+
| {
|
|
65
|
+
readonly kind: "update";
|
|
66
|
+
readonly displayPath: string;
|
|
67
|
+
readonly absPath: string;
|
|
68
|
+
readonly prepared: PreparedEdit;
|
|
69
|
+
readonly diff: string;
|
|
70
|
+
readonly isHashline: boolean;
|
|
71
|
+
}
|
|
72
|
+
| {
|
|
73
|
+
readonly kind: "move";
|
|
74
|
+
readonly displayPath: string;
|
|
75
|
+
readonly moveToDisplay: string;
|
|
76
|
+
readonly absPath: string;
|
|
77
|
+
readonly destAbsPath: string;
|
|
78
|
+
readonly destKey: string;
|
|
79
|
+
readonly prepared: PreparedEdit;
|
|
80
|
+
readonly diff: string;
|
|
81
|
+
readonly isHashline: boolean;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
async function assertPathAbsent(absPath: string): Promise<void> {
|
|
85
|
+
try {
|
|
86
|
+
await lstat(absPath);
|
|
87
|
+
throw new EditError("INVALID_INPUT", `Destination path already exists: ${absPath}`);
|
|
88
|
+
} catch (e) {
|
|
89
|
+
if (e instanceof EditError) throw e;
|
|
90
|
+
if ((e as { code?: string })?.code !== "ENOENT") {
|
|
91
|
+
throw new EditError("UNSUPPORTED_FILE", `Cannot inspect destination ${absPath}: ${String(e)}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function plannerForPatchOp(op: Extract<ReturnType<typeof parseMultiFilePatch>[number], { type: "update" }>) {
|
|
97
|
+
if (op.hashlines) {
|
|
98
|
+
return (before: string) =>
|
|
99
|
+
op.hashlines!.length ? planHashlineEdits(before, op.hashlines!) : { before, after: before, ranges: [], changed: false };
|
|
100
|
+
}
|
|
101
|
+
if (op.searchReplace) return (before: string) => planEdits(before, op.searchReplace!);
|
|
102
|
+
return (before: string) => planHunks(before, op.hunks);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Execute a multi-file patch with all-or-nothing pre-flight validation and deadlock-free path locking. */
|
|
106
|
+
export async function executeApplyPatch(
|
|
107
|
+
cwd: string,
|
|
108
|
+
patchText: string,
|
|
109
|
+
scope: ReadScope,
|
|
110
|
+
signal?: AbortSignal,
|
|
111
|
+
): Promise<{ text: string; details: ApplyPatchDetails }> {
|
|
112
|
+
checkEditAbort(signal);
|
|
113
|
+
const rawOps = parseMultiFilePatch(patchText);
|
|
114
|
+
const resolvedPaths: string[] = [];
|
|
115
|
+
const resolvedOps = rawOps.map((op) => {
|
|
116
|
+
const absPath = resolveEditPath(op.path, cwd);
|
|
117
|
+
resolvedPaths.push(absPath);
|
|
118
|
+
if (op.type === "update" && op.moveTo) {
|
|
119
|
+
const destAbsPath = resolveEditPath(op.moveTo, cwd);
|
|
120
|
+
resolvedPaths.push(destAbsPath);
|
|
121
|
+
return { op, absPath, destAbsPath };
|
|
122
|
+
}
|
|
123
|
+
return { op, absPath, destAbsPath: undefined };
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// Reject duplicate targets (including case-folded aliases on Windows) before taking locks or mutating anything.
|
|
127
|
+
const seenTargets = new Set<string>();
|
|
128
|
+
for (const { absPath, destAbsPath } of resolvedOps) {
|
|
129
|
+
const k = await canonicalKey(absPath);
|
|
130
|
+
if (seenTargets.has(k)) {
|
|
131
|
+
throw new EditError("INVALID_INPUT", `Patch targets the same path more than once: ${absPath}`);
|
|
132
|
+
}
|
|
133
|
+
seenTargets.add(k);
|
|
134
|
+
if (destAbsPath) {
|
|
135
|
+
const dk = await canonicalKey(destAbsPath);
|
|
136
|
+
if (seenTargets.has(dk)) {
|
|
137
|
+
throw new EditError("INVALID_INPUT", `Patch destination conflicts with another target in the same patch: ${destAbsPath}`);
|
|
138
|
+
}
|
|
139
|
+
seenTargets.add(dk);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const epoch = scope.epoch;
|
|
144
|
+
return withPathLocks(resolvedPaths, async () => {
|
|
145
|
+
checkEditAbort(signal);
|
|
146
|
+
if (scope.epoch !== epoch) {
|
|
147
|
+
throw new EditError("STALE_PLAN", "Session changed before apply_patch execution.");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Phase 1: Validate every file completely in memory and aggregate failures so multi-file errors fix in one turn.
|
|
151
|
+
const staged: PreparedPatchOp[] = [];
|
|
152
|
+
const preflightErrors: { path: string; error: unknown }[] = [];
|
|
153
|
+
for (const { op, absPath, destAbsPath } of resolvedOps) {
|
|
154
|
+
checkEditAbort(signal);
|
|
155
|
+
try {
|
|
156
|
+
if (op.type === "add") {
|
|
157
|
+
await assertPathAbsent(absPath);
|
|
158
|
+
const prepared = await prepareNewFileWrite(absPath, op.content);
|
|
159
|
+
staged.push({ kind: "add", displayPath: op.path, absPath, key: await canonicalKey(absPath), prepared });
|
|
160
|
+
} else if (op.type === "delete") {
|
|
161
|
+
const snapshot = await loadSnapshot(absPath, scope);
|
|
162
|
+
staged.push({ kind: "delete", displayPath: op.path, absPath: snapshot.absPath, snapshot });
|
|
163
|
+
} else if (destAbsPath) {
|
|
164
|
+
await assertPathAbsent(destAbsPath);
|
|
165
|
+
const prepared = await prepareEditWithPlan(absPath, plannerForPatchOp(op), scope);
|
|
166
|
+
const { diff } = buildEditDiff(op.moveTo!, prepared.plan);
|
|
167
|
+
staged.push({
|
|
168
|
+
kind: "move",
|
|
169
|
+
displayPath: op.path,
|
|
170
|
+
moveToDisplay: op.moveTo!,
|
|
171
|
+
absPath: prepared.snapshot.absPath,
|
|
172
|
+
destAbsPath,
|
|
173
|
+
destKey: await canonicalKey(destAbsPath),
|
|
174
|
+
prepared,
|
|
175
|
+
diff,
|
|
176
|
+
isHashline: !!op.hashlines,
|
|
177
|
+
});
|
|
178
|
+
} else {
|
|
179
|
+
const prepared = await prepareEditWithPlan(absPath, plannerForPatchOp(op), scope);
|
|
180
|
+
const { diff } = buildEditDiff(op.path, prepared.plan);
|
|
181
|
+
staged.push({ kind: "update", displayPath: op.path, absPath: prepared.snapshot.absPath, prepared, diff, isHashline: !!op.hashlines });
|
|
182
|
+
}
|
|
183
|
+
} catch (err) {
|
|
184
|
+
preflightErrors.push({ path: op.path, error: err });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (preflightErrors.length === 1) throw preflightErrors[0].error;
|
|
188
|
+
if (preflightErrors.length > 1) {
|
|
189
|
+
const first = preflightErrors[0].error;
|
|
190
|
+
const code = first instanceof EditError ? first.code : "INVALID_INPUT";
|
|
191
|
+
const summary = preflightErrors
|
|
192
|
+
.slice(0, 8)
|
|
193
|
+
.map(({ path: p, error }) => `- ${p}: ${error instanceof Error ? error.message : String(error)}`)
|
|
194
|
+
.join("\n");
|
|
195
|
+
const more = preflightErrors.length > 8 ? `\n... (${preflightErrors.length - 8} more file errors)` : "";
|
|
196
|
+
throw new EditError(code, `Pre-flight failed for ${preflightErrors.length} file(s); zero files modified:\n${summary}${more}`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Phase 2: Commit validated changes atomically per file under one shared undo batchId so a single
|
|
200
|
+
// `/charset-undo` reverts the whole patch (including moves and partial commits).
|
|
201
|
+
const batchId = allocateBatchId();
|
|
202
|
+
const results: ApplyPatchFileResult[] = [];
|
|
203
|
+
const summaryLines: string[] = [];
|
|
204
|
+
const committedLabels: string[] = [];
|
|
205
|
+
const autoCommitPaths: string[] = [];
|
|
206
|
+
let autoCommitRule: ResolvedConfig | null = null;
|
|
207
|
+
const trackCommit = (rule: ResolvedConfig | null, ...paths: string[]) => {
|
|
208
|
+
if (rule?.autoCommit) {
|
|
209
|
+
autoCommitRule ??= rule;
|
|
210
|
+
autoCommitPaths.push(...paths);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
try {
|
|
215
|
+
for (const item of staged) {
|
|
216
|
+
checkEditAbort(signal);
|
|
217
|
+
if (item.kind === "update") {
|
|
218
|
+
await commitPlanLocked(item.prepared, scope, epoch, signal, undefined, true, batchId);
|
|
219
|
+
const action = item.prepared.plan.changed ? "updated" : "unchanged";
|
|
220
|
+
results.push({ action, path: item.displayPath, diff: item.diff });
|
|
221
|
+
if (action === "updated") {
|
|
222
|
+
committedLabels.push(`M ${item.displayPath}`);
|
|
223
|
+
trackCommit(item.prepared.snapshot.rule, item.absPath);
|
|
224
|
+
}
|
|
225
|
+
if (item.isHashline && item.prepared.plan.changed) {
|
|
226
|
+
const upd = formatUpdatedHashlines(item.prepared.plan, 8, 400);
|
|
227
|
+
const delta = upd.lineDelta ? ` (Δ${upd.lineDelta > 0 ? "+" : ""}${upd.lineDelta})` : "";
|
|
228
|
+
summaryLines.push(`M ${item.displayPath}${delta}${upd.lines.length ? "\n " + upd.lines.join("\n ") : ""}`);
|
|
229
|
+
} else {
|
|
230
|
+
summaryLines.push(`${action === "updated" ? "M" : "="} ${item.displayPath}`);
|
|
231
|
+
}
|
|
232
|
+
} else if (item.kind === "add") {
|
|
233
|
+
const { plan, g1, bytes, text, bomLen, provenLossless } = item.prepared;
|
|
234
|
+
for (const w of plan.warnings) pushEncodingNote(item.absPath, w);
|
|
235
|
+
if (g1.note) pushEncodingNote(item.absPath, g1.note);
|
|
236
|
+
await mkdir(path.dirname(item.absPath), { recursive: true });
|
|
237
|
+
await atomicReplace(item.absPath, bytes, null, undefined, signal);
|
|
238
|
+
await recordWrite(item.absPath, null, bytes, "add", batchId);
|
|
239
|
+
committedLabels.push(`A ${item.displayPath}`);
|
|
240
|
+
trackCommit(plan.rule, item.absPath);
|
|
241
|
+
if (plan.rule && plan.rule.verifyWrite !== false) {
|
|
242
|
+
const problem = await verifyWritten(item.absPath, bytes, text, g1.encoding, plan.rule, bomLen, provenLossless);
|
|
243
|
+
if (problem) {
|
|
244
|
+
throw new EditError("VERIFY_FAILED", `Post-write verification failed for ${item.displayPath}: ${problem}`, "unknown");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
afterWrite(item.absPath, bytes, scope, item.key, epoch);
|
|
248
|
+
results.push({ action: "added", path: item.displayPath });
|
|
249
|
+
summaryLines.push(`A ${item.displayPath}`);
|
|
250
|
+
} else if (item.kind === "delete") {
|
|
251
|
+
const cur = await readFile(item.absPath).catch(() => null);
|
|
252
|
+
if (!cur?.equals(item.snapshot.raw)) {
|
|
253
|
+
throw new EditError("STALE_PLAN", `Target file changed before deletion: ${item.displayPath}`);
|
|
254
|
+
}
|
|
255
|
+
await unlink(item.absPath);
|
|
256
|
+
await recordWrite(item.absPath, item.snapshot.raw, null, "delete", batchId);
|
|
257
|
+
committedLabels.push(`D ${item.displayPath}`);
|
|
258
|
+
trackCommit(item.snapshot.rule, item.absPath);
|
|
259
|
+
afterWrite(item.absPath, null, scope, item.snapshot.key, epoch);
|
|
260
|
+
results.push({ action: "deleted", path: item.displayPath });
|
|
261
|
+
summaryLines.push(`D ${item.displayPath}`);
|
|
262
|
+
} else {
|
|
263
|
+
// Move: atomically write destination first, verify read-back, record destination add immediately
|
|
264
|
+
// so `/charset-undo b<batchId>` can clean it up if removing the source fails, then remove source.
|
|
265
|
+
const { snapshot, bytes } = item.prepared;
|
|
266
|
+
const curSrc = await readFile(item.absPath).catch(() => null);
|
|
267
|
+
if (!curSrc?.equals(snapshot.raw)) {
|
|
268
|
+
throw new EditError("STALE_PLAN", `Source file changed before move: ${item.displayPath}`);
|
|
269
|
+
}
|
|
270
|
+
await mkdir(path.dirname(item.destAbsPath), { recursive: true });
|
|
271
|
+
await atomicReplace(item.destAbsPath, bytes, null, undefined, signal);
|
|
272
|
+
if (snapshot.rule.verifyWrite !== false) {
|
|
273
|
+
const problem = await verifyWritten(
|
|
274
|
+
item.destAbsPath,
|
|
275
|
+
bytes,
|
|
276
|
+
item.prepared.plan.after,
|
|
277
|
+
snapshot.encoding,
|
|
278
|
+
snapshot.rule,
|
|
279
|
+
snapshot.bomLength,
|
|
280
|
+
true,
|
|
281
|
+
);
|
|
282
|
+
if (problem) {
|
|
283
|
+
throw new EditError("VERIFY_FAILED", `Post-write verification failed for moved destination ${item.moveToDisplay}: ${problem}`, "unknown");
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
const written = await readFile(item.destAbsPath).catch(() => null);
|
|
287
|
+
if (!written?.equals(bytes)) {
|
|
288
|
+
throw new EditError("VERIFY_FAILED", `Post-write verification failed for moved destination ${item.moveToDisplay}.`, "unknown");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
await recordWrite(item.destAbsPath, null, bytes, "add", batchId);
|
|
292
|
+
afterWrite(item.destAbsPath, bytes, scope, item.destKey, epoch);
|
|
293
|
+
const destLabelIdx = committedLabels.length;
|
|
294
|
+
committedLabels.push(`A ${item.moveToDisplay}`);
|
|
295
|
+
await unlink(item.absPath);
|
|
296
|
+
await recordWrite(item.absPath, snapshot.raw, null, "delete", batchId);
|
|
297
|
+
committedLabels[destLabelIdx] = `R ${item.displayPath} -> ${item.moveToDisplay}`;
|
|
298
|
+
trackCommit(snapshot.rule, item.absPath, item.destAbsPath);
|
|
299
|
+
afterWrite(item.absPath, null, scope, snapshot.key, epoch);
|
|
300
|
+
results.push({ action: "moved", path: item.displayPath, movedTo: item.moveToDisplay, diff: item.diff });
|
|
301
|
+
if (item.isHashline && item.prepared.plan.changed) {
|
|
302
|
+
const upd = formatUpdatedHashlines(item.prepared.plan, 8, 400);
|
|
303
|
+
const delta = upd.lineDelta ? ` (Δ${upd.lineDelta > 0 ? "+" : ""}${upd.lineDelta})` : "";
|
|
304
|
+
summaryLines.push(`R ${item.displayPath} -> ${item.moveToDisplay}${delta}${upd.lines.length ? "\n " + upd.lines.join("\n ") : ""}`);
|
|
305
|
+
} else {
|
|
306
|
+
summaryLines.push(`R ${item.displayPath} -> ${item.moveToDisplay}`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (committedLabels.length > 0) {
|
|
312
|
+
const baseMsg = error instanceof Error ? error.message : String(error);
|
|
313
|
+
const code = error instanceof EditError ? error.code : "COMMIT_UNKNOWN";
|
|
314
|
+
throw new EditError(
|
|
315
|
+
code,
|
|
316
|
+
`Partial commit (${committedLabels.join(", ")} already written; use /charset-undo b${batchId} to revert): ${baseMsg}`,
|
|
317
|
+
"unknown",
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
throw error;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (autoCommitPaths.length > 0 && autoCommitRule) {
|
|
324
|
+
await autoCommitBatch(autoCommitPaths, autoCommitRule, "patch", (note) => pushEncodingNote(autoCommitPaths[0], note));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const collectedNotes: string[] = [];
|
|
328
|
+
for (const p of resolvedPaths) {
|
|
329
|
+
for (const n of drainEncodingNotes(p)) {
|
|
330
|
+
if (collectedNotes.length < 6 && !collectedNotes.includes(n)) collectedNotes.push(n);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const suffix = notesToSuffix(collectedNotes);
|
|
334
|
+
return {
|
|
335
|
+
text: `Applied patch to ${results.length} file(s):\n${summaryLines.join("\n")}${suffix}`,
|
|
336
|
+
details: { files: results, ...(committedLabels.length > 0 ? { batchId } : {}) },
|
|
337
|
+
};
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function createApplyPatchDefinition(cwd: string, scope: ReadScope): ToolDefinition<typeof applyPatchSchema, ApplyPatchDetails> {
|
|
342
|
+
return {
|
|
343
|
+
name: "apply_patch",
|
|
344
|
+
label: "apply_patch (encoding aware)",
|
|
345
|
+
description:
|
|
346
|
+
"Atomic pre-validated multi-file patch: Codex (*** Begin Patch with Update/Hashline/Add/Delete/Move), Aider S/R, or unified diff.",
|
|
347
|
+
promptSnippet: "Atomic multi-file patch (Codex/Hashline/Aider/diff)",
|
|
348
|
+
parameters: applyPatchSchema,
|
|
349
|
+
constrainedSampling: { type: "json_schema", strict: "prefer" },
|
|
350
|
+
renderShell: "self",
|
|
351
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx): Promise<AgentToolResult<ApplyPatchDetails>> {
|
|
352
|
+
const res = await executeApplyPatch(ctx?.cwd || cwd, params.patch, scope, signal);
|
|
353
|
+
return {
|
|
354
|
+
content: [{ type: "text", text: res.text }],
|
|
355
|
+
details: res.details,
|
|
356
|
+
};
|
|
357
|
+
},
|
|
358
|
+
renderCall(input, theme, context) {
|
|
359
|
+
const pad = "outputPad" in context && typeof context.outputPad === "number" ? context.outputPad : 1;
|
|
360
|
+
const box = new Box(pad, 1, (s) => theme.bg("toolPendingBg", s));
|
|
361
|
+
let targets = "(patch)";
|
|
362
|
+
if (typeof input?.patch === "string" && input.patch.trim()) {
|
|
363
|
+
try {
|
|
364
|
+
const ops = parseMultiFilePatch(input.patch);
|
|
365
|
+
targets = `${ops.length} file(s): ${ops.slice(0, 4).map((o) => o.path).join(", ")}${ops.length > 4 ? ", ..." : ""}`;
|
|
366
|
+
} catch { /* Streaming partial patch: wait for complete arguments. */ }
|
|
367
|
+
}
|
|
368
|
+
box.addChild(new Text(`${theme.fg("toolTitle", theme.bold("apply_patch"))} ${targets}`, 0, 0));
|
|
369
|
+
return box;
|
|
370
|
+
},
|
|
371
|
+
renderResult(result, _options, theme, context) {
|
|
372
|
+
const pad = "outputPad" in context && typeof context.outputPad === "number" ? context.outputPad : 1;
|
|
373
|
+
const box = new Box(pad, 0, (s) => theme.bg(context.isError ? "toolErrorBg" : "toolSuccessBg", s));
|
|
374
|
+
const summary = result.content.filter((p) => p.type === "text").map((p) => p.text).join("\n");
|
|
375
|
+
box.addChild(new Text(summary, 0, 0));
|
|
376
|
+
if (!context.isError && context.expanded && result.details?.files?.length) {
|
|
377
|
+
for (const f of result.details.files) {
|
|
378
|
+
if (!f.diff) continue;
|
|
379
|
+
box.addChild(new Spacer(1));
|
|
380
|
+
let rendered = f.diff;
|
|
381
|
+
try { rendered = renderDiff(f.diff, { filePath: f.movedTo ?? f.path }); } catch { /* Plain text fallback. */ }
|
|
382
|
+
box.addChild(new Text(`${theme.bold(f.movedTo ? `${f.path} -> ${f.movedTo}` : f.path)}\n${rendered}`, 0, 0));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return box;
|
|
386
|
+
},
|
|
387
|
+
};
|
|
388
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export type EditErrorCode =
|
|
2
|
+
| "INVALID_INPUT" | "NOT_FOUND" | "AMBIGUOUS_MATCH" | "OVERLAPPING_EDITS" | "HASH_MISMATCH"
|
|
3
|
+
| "UNSUPPORTED_FILE" | "UNENCODABLE" | "AMBIGUOUS_ENCODING" | "STALE_READ" | "STALE_PLAN"
|
|
4
|
+
| "CANCELLED" | "TEMP_WRITE_FAILED" | "VERIFY_FAILED" | "COMMIT_UNKNOWN";
|
|
5
|
+
|
|
6
|
+
export class EditError extends Error {
|
|
7
|
+
constructor(readonly code: EditErrorCode, message: string,
|
|
8
|
+
readonly commitState: "not_applied" | "unknown" = "not_applied") {
|
|
9
|
+
super(`[${code}; ${commitState}] ${message}`);
|
|
10
|
+
this.name = "EditError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function lineAt(text: string, offset: number): number {
|
|
15
|
+
let count = 1;
|
|
16
|
+
for (let i = 0; i < offset; i++) if (text.charCodeAt(i) === 10) count++;
|
|
17
|
+
return count;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Hints are actual source lines, never replacement candidates selected by the tool. */
|
|
21
|
+
export function suggestLines(text: string, oldText: string): string {
|
|
22
|
+
const first = oldText.split(/\r?\n/).find((line) => line.trim())?.trim().slice(0, 120);
|
|
23
|
+
if (!first) return "";
|
|
24
|
+
const tokens = first.match(/[\p{L}\p{N}_]+/gu)?.filter((t) => t.length >= 2).slice(0, 8) ?? [];
|
|
25
|
+
const hints: { score: number; line: number; content: string }[] = [];
|
|
26
|
+
let start = 0;
|
|
27
|
+
let line = 1;
|
|
28
|
+
while (start < text.length) {
|
|
29
|
+
const next = text.indexOf("\n", start);
|
|
30
|
+
const raw = text.slice(start, next < 0 ? text.length : next);
|
|
31
|
+
const trimmed = raw.trim();
|
|
32
|
+
const score = trimmed.includes(first) ? 100 : tokens.reduce((sum, token) => sum + Number(trimmed.includes(token)), 0);
|
|
33
|
+
if (score && (hints.length < 3 || score > hints[2].score)) {
|
|
34
|
+
// JSON can use six bytes per code unit. Three 200-unit prefixes fit within 4 KiB.
|
|
35
|
+
hints.push({ score, line, content: raw.replace(/\r$/, "").slice(0, 200) });
|
|
36
|
+
hints.sort((a, b) => b.score - a.score || a.line - b.line);
|
|
37
|
+
if (hints.length > 3) hints.pop();
|
|
38
|
+
}
|
|
39
|
+
if (next < 0) break;
|
|
40
|
+
start = next + 1;
|
|
41
|
+
line++;
|
|
42
|
+
}
|
|
43
|
+
return hints.length ? "\nSource lines:\n" +
|
|
44
|
+
hints.map((hint) => `L${hint.line}: ${JSON.stringify(hint.content)}`).join("\n") : "";
|
|
45
|
+
}
|