pi-charset 0.1.5 → 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.
@@ -0,0 +1,275 @@
1
+ // Pure, Pi-independent multi-file `apply_patch` engine shared by Pi's apply_patch tool and pi-charset-mcp.
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 {
6
+ afterWrite,
7
+ atomicReplace,
8
+ canonicalKey,
9
+ checkEditAbort,
10
+ commitPlanLocked,
11
+ loadSnapshot,
12
+ prepareEditWithPlan,
13
+ prepareNewFileWrite,
14
+ verifyWritten,
15
+ withPathLocks,
16
+ type FileSnapshot,
17
+ type PreparedEdit,
18
+ type ReadScope,
19
+ } from "../operations";
20
+ import { allocateBatchId, autoCommitBatch, recordWrite } from "../journal";
21
+ import type { ResolvedConfig } from "../config";
22
+ import { drainEncodingNotes, notesToSuffix, pushEncodingNote } from "../notify";
23
+ import { EditError, lineAt } from "./diagnostics";
24
+ import { formatUpdatedHashlines, planHashlineEdits } from "./hashline";
25
+ import { planEdits, type PlannedText } from "./plan";
26
+ import { parseMultiFilePatch, planHunks } from "./patch";
27
+ import { resolveEditPath } from "./paths";
28
+
29
+ export interface ApplyPatchFileResult {
30
+ readonly action: "added" | "updated" | "unchanged" | "deleted" | "moved";
31
+ readonly path: string;
32
+ readonly movedTo?: string;
33
+ readonly diff?: string;
34
+ }
35
+
36
+ export interface ApplyPatchDetails {
37
+ readonly files: readonly ApplyPatchFileResult[];
38
+ readonly batchId?: number;
39
+ }
40
+
41
+ type PreparedPatchOp =
42
+ | { readonly kind: "add"; readonly displayPath: string; readonly absPath: string; readonly key: string; readonly prepared: Awaited<ReturnType<typeof prepareNewFileWrite>> }
43
+ | { readonly kind: "delete"; readonly displayPath: string; readonly absPath: string; readonly snapshot: FileSnapshot }
44
+ | { readonly kind: "update"; readonly displayPath: string; readonly absPath: string; readonly prepared: PreparedEdit; readonly diff: string; readonly isHashline: boolean }
45
+ | { readonly kind: "move"; readonly displayPath: string; readonly moveToDisplay: string; readonly absPath: string; readonly destAbsPath: string; readonly destKey: string; readonly prepared: PreparedEdit; readonly diff: string; readonly isHashline: boolean };
46
+
47
+ /** Lightweight zero-dependency unified diff summary used when no Pi TUI diff renderer is supplied. */
48
+ export function compactRangeDiff(plan: PlannedText): string {
49
+ if (!plan.changed || plan.ranges.length === 0) return "";
50
+ const out: string[] = [];
51
+ for (const r of plan.ranges.slice(0, 12)) {
52
+ const startLine = lineAt(plan.before, r.start);
53
+ const oldLines = plan.before.slice(r.start, r.end).replace(/\r\n/g, "\n").split("\n");
54
+ const newLines = r.text.replace(/\r\n/g, "\n").split("\n");
55
+ out.push(`@@ -${startLine},${oldLines.length} +${startLine},${newLines.length} @@`);
56
+ for (const l of oldLines.slice(0, 12)) out.push(`-${l}`);
57
+ for (const l of newLines.slice(0, 12)) out.push(`+${l}`);
58
+ }
59
+ return out.join("\n");
60
+ }
61
+
62
+ async function assertPathAbsent(absPath: string): Promise<void> {
63
+ try {
64
+ await lstat(absPath);
65
+ throw new EditError("INVALID_INPUT", `Destination path already exists: ${absPath}`);
66
+ } catch (e) {
67
+ if (e instanceof EditError) throw e;
68
+ if ((e as { code?: string })?.code !== "ENOENT") {
69
+ throw new EditError("UNSUPPORTED_FILE", `Cannot inspect destination ${absPath}: ${String(e)}`);
70
+ }
71
+ }
72
+ }
73
+
74
+ function plannerForPatchOp(op: Extract<ReturnType<typeof parseMultiFilePatch>[number], { type: "update" }>) {
75
+ if (op.hashlines) {
76
+ return (before: string) =>
77
+ op.hashlines!.length ? planHashlineEdits(before, op.hashlines!) : { before, after: before, ranges: [], changed: false };
78
+ }
79
+ if (op.searchReplace) return (before: string) => planEdits(before, op.searchReplace!);
80
+ return (before: string) => planHunks(before, op.hunks);
81
+ }
82
+
83
+ /** Execute a multi-file patch with all-or-nothing pre-flight validation and deadlock-free path locking. */
84
+ export async function executeApplyPatch(
85
+ cwd: string,
86
+ patchText: string,
87
+ scope: ReadScope,
88
+ signal?: AbortSignal,
89
+ formatDiff: (displayPath: string, plan: PlannedText) => string = (_p, plan) => compactRangeDiff(plan),
90
+ ): Promise<{ text: string; details: ApplyPatchDetails }> {
91
+ checkEditAbort(signal);
92
+ const rawOps = parseMultiFilePatch(patchText);
93
+ const resolvedPaths: string[] = [];
94
+ const resolvedOps = rawOps.map((op) => {
95
+ const absPath = resolveEditPath(op.path, cwd);
96
+ resolvedPaths.push(absPath);
97
+ if (op.type === "update" && op.moveTo) {
98
+ const destAbsPath = resolveEditPath(op.moveTo, cwd);
99
+ resolvedPaths.push(destAbsPath);
100
+ return { op, absPath, destAbsPath };
101
+ }
102
+ return { op, absPath, destAbsPath: undefined };
103
+ });
104
+
105
+ const seenTargets = new Set<string>();
106
+ for (const { absPath, destAbsPath } of resolvedOps) {
107
+ const k = await canonicalKey(absPath);
108
+ if (seenTargets.has(k)) throw new EditError("INVALID_INPUT", `Patch targets the same path more than once: ${absPath}`);
109
+ seenTargets.add(k);
110
+ if (destAbsPath) {
111
+ const dk = await canonicalKey(destAbsPath);
112
+ if (seenTargets.has(dk)) throw new EditError("INVALID_INPUT", `Patch destination conflicts with another target in the same patch: ${destAbsPath}`);
113
+ seenTargets.add(dk);
114
+ }
115
+ }
116
+
117
+ const epoch = scope.epoch;
118
+ return withPathLocks(resolvedPaths, async () => {
119
+ checkEditAbort(signal);
120
+ if (scope.epoch !== epoch) throw new EditError("STALE_PLAN", "Session changed before apply_patch execution.");
121
+
122
+ const staged: PreparedPatchOp[] = [];
123
+ const preflightErrors: { path: string; error: unknown }[] = [];
124
+ for (const { op, absPath, destAbsPath } of resolvedOps) {
125
+ checkEditAbort(signal);
126
+ try {
127
+ if (op.type === "add") {
128
+ await assertPathAbsent(absPath);
129
+ const prepared = await prepareNewFileWrite(absPath, op.content);
130
+ staged.push({ kind: "add", displayPath: op.path, absPath, key: await canonicalKey(absPath), prepared });
131
+ } else if (op.type === "delete") {
132
+ const snapshot = await loadSnapshot(absPath, scope);
133
+ staged.push({ kind: "delete", displayPath: op.path, absPath: snapshot.absPath, snapshot });
134
+ } else if (destAbsPath) {
135
+ await assertPathAbsent(destAbsPath);
136
+ const prepared = await prepareEditWithPlan(absPath, plannerForPatchOp(op), scope);
137
+ const diff = formatDiff(op.moveTo!, prepared.plan);
138
+ staged.push({
139
+ kind: "move", displayPath: op.path, moveToDisplay: op.moveTo!,
140
+ absPath: prepared.snapshot.absPath, destAbsPath, destKey: await canonicalKey(destAbsPath),
141
+ prepared, diff, isHashline: !!op.hashlines,
142
+ });
143
+ } else {
144
+ const prepared = await prepareEditWithPlan(absPath, plannerForPatchOp(op), scope);
145
+ const diff = formatDiff(op.path, prepared.plan);
146
+ staged.push({ kind: "update", displayPath: op.path, absPath: prepared.snapshot.absPath, prepared, diff, isHashline: !!op.hashlines });
147
+ }
148
+ } catch (err) {
149
+ preflightErrors.push({ path: op.path, error: err });
150
+ }
151
+ }
152
+ if (preflightErrors.length === 1) throw preflightErrors[0].error;
153
+ if (preflightErrors.length > 1) {
154
+ const first = preflightErrors[0].error;
155
+ const code = first instanceof EditError ? first.code : "INVALID_INPUT";
156
+ const summary = preflightErrors.slice(0, 8).map(({ path: p, error }) => `- ${p}: ${error instanceof Error ? error.message : String(error)}`).join("\n");
157
+ const more = preflightErrors.length > 8 ? `\n... (${preflightErrors.length - 8} more file errors)` : "";
158
+ throw new EditError(code, `Pre-flight failed for ${preflightErrors.length} file(s); zero files modified:\n${summary}${more}`);
159
+ }
160
+
161
+ const batchId = allocateBatchId();
162
+ const results: ApplyPatchFileResult[] = [];
163
+ const summaryLines: string[] = [];
164
+ const committedLabels: string[] = [];
165
+ const autoCommitPaths: string[] = [];
166
+ let autoCommitRule: ResolvedConfig | null = null;
167
+ const trackCommit = (rule: ResolvedConfig | null, ...paths: string[]) => {
168
+ if (rule?.autoCommit) {
169
+ autoCommitRule ??= rule;
170
+ autoCommitPaths.push(...paths);
171
+ }
172
+ };
173
+
174
+ try {
175
+ for (const item of staged) {
176
+ checkEditAbort(signal);
177
+ if (item.kind === "update") {
178
+ await commitPlanLocked(item.prepared, scope, epoch, signal, undefined, true, batchId);
179
+ const action = item.prepared.plan.changed ? "updated" : "unchanged";
180
+ results.push({ action, path: item.displayPath, diff: item.diff });
181
+ if (action === "updated") {
182
+ committedLabels.push(`M ${item.displayPath}`);
183
+ trackCommit(item.prepared.snapshot.rule, item.absPath);
184
+ }
185
+ if (item.isHashline && item.prepared.plan.changed) {
186
+ const upd = formatUpdatedHashlines(item.prepared.plan, 8, 400);
187
+ const delta = upd.lineDelta ? ` (Δ${upd.lineDelta > 0 ? "+" : ""}${upd.lineDelta})` : "";
188
+ summaryLines.push(`M ${item.displayPath}${delta}${upd.lines.length ? "\n " + upd.lines.join("\n ") : ""}`);
189
+ } else {
190
+ summaryLines.push(`${action === "updated" ? "M" : "="} ${item.displayPath}`);
191
+ }
192
+ } else if (item.kind === "add") {
193
+ const { plan, g1, bytes, text, bomLen, provenLossless } = item.prepared;
194
+ for (const w of plan.warnings) pushEncodingNote(item.absPath, w);
195
+ if (g1.note) pushEncodingNote(item.absPath, g1.note);
196
+ await mkdir(path.dirname(item.absPath), { recursive: true });
197
+ await atomicReplace(item.absPath, bytes, null, undefined, signal);
198
+ await recordWrite(item.absPath, null, bytes, "add", batchId);
199
+ committedLabels.push(`A ${item.displayPath}`);
200
+ trackCommit(plan.rule, item.absPath);
201
+ if (plan.rule && plan.rule.verifyWrite !== false) {
202
+ const problem = await verifyWritten(item.absPath, bytes, text, g1.encoding, plan.rule, bomLen, provenLossless);
203
+ if (problem) throw new EditError("VERIFY_FAILED", `Post-write verification failed for ${item.displayPath}: ${problem}`, "unknown");
204
+ }
205
+ afterWrite(item.absPath, bytes, scope, item.key, epoch);
206
+ results.push({ action: "added", path: item.displayPath });
207
+ summaryLines.push(`A ${item.displayPath}`);
208
+ } else if (item.kind === "delete") {
209
+ const cur = await readFile(item.absPath).catch(() => null);
210
+ if (!cur?.equals(item.snapshot.raw)) throw new EditError("STALE_PLAN", `Target file changed before deletion: ${item.displayPath}`);
211
+ await unlink(item.absPath);
212
+ await recordWrite(item.absPath, item.snapshot.raw, null, "delete", batchId);
213
+ committedLabels.push(`D ${item.displayPath}`);
214
+ trackCommit(item.snapshot.rule, item.absPath);
215
+ afterWrite(item.absPath, null, scope, item.snapshot.key, epoch);
216
+ results.push({ action: "deleted", path: item.displayPath });
217
+ summaryLines.push(`D ${item.displayPath}`);
218
+ } else {
219
+ const { snapshot, bytes } = item.prepared;
220
+ const curSrc = await readFile(item.absPath).catch(() => null);
221
+ if (!curSrc?.equals(snapshot.raw)) throw new EditError("STALE_PLAN", `Source file changed before move: ${item.displayPath}`);
222
+ await mkdir(path.dirname(item.destAbsPath), { recursive: true });
223
+ await atomicReplace(item.destAbsPath, bytes, null, undefined, signal);
224
+ if (snapshot.rule.verifyWrite !== false) {
225
+ const problem = await verifyWritten(item.destAbsPath, bytes, item.prepared.plan.after, snapshot.encoding, snapshot.rule, snapshot.bomLength, true);
226
+ if (problem) throw new EditError("VERIFY_FAILED", `Post-write verification failed for moved destination ${item.moveToDisplay}: ${problem}`, "unknown");
227
+ } else {
228
+ const written = await readFile(item.destAbsPath).catch(() => null);
229
+ if (!written?.equals(bytes)) throw new EditError("VERIFY_FAILED", `Post-write verification failed for moved destination ${item.moveToDisplay}.`, "unknown");
230
+ }
231
+ await recordWrite(item.destAbsPath, null, bytes, "add", batchId);
232
+ afterWrite(item.destAbsPath, bytes, scope, item.destKey, epoch);
233
+ const destLabelIdx = committedLabels.length;
234
+ committedLabels.push(`A ${item.moveToDisplay}`);
235
+ await unlink(item.absPath);
236
+ await recordWrite(item.absPath, snapshot.raw, null, "delete", batchId);
237
+ committedLabels[destLabelIdx] = `R ${item.displayPath} -> ${item.moveToDisplay}`;
238
+ trackCommit(snapshot.rule, item.absPath, item.destAbsPath);
239
+ afterWrite(item.absPath, null, scope, snapshot.key, epoch);
240
+ results.push({ action: "moved", path: item.displayPath, movedTo: item.moveToDisplay, diff: item.diff });
241
+ if (item.isHashline && item.prepared.plan.changed) {
242
+ const upd = formatUpdatedHashlines(item.prepared.plan, 8, 400);
243
+ const delta = upd.lineDelta ? ` (Δ${upd.lineDelta > 0 ? "+" : ""}${upd.lineDelta})` : "";
244
+ summaryLines.push(`R ${item.displayPath} -> ${item.moveToDisplay}${delta}${upd.lines.length ? "\n " + upd.lines.join("\n ") : ""}`);
245
+ } else {
246
+ summaryLines.push(`R ${item.displayPath} -> ${item.moveToDisplay}`);
247
+ }
248
+ }
249
+ }
250
+ } catch (error) {
251
+ if (committedLabels.length > 0) {
252
+ const baseMsg = error instanceof Error ? error.message : String(error);
253
+ const code = error instanceof EditError ? error.code : "COMMIT_UNKNOWN";
254
+ throw new EditError(code, `Partial commit (${committedLabels.join(", ")} already written; use /charset-undo b${batchId} to revert): ${baseMsg}`, "unknown");
255
+ }
256
+ throw error;
257
+ }
258
+
259
+ if (autoCommitPaths.length > 0 && autoCommitRule) {
260
+ await autoCommitBatch(autoCommitPaths, autoCommitRule, "patch", (note) => pushEncodingNote(autoCommitPaths[0], note));
261
+ }
262
+
263
+ const collectedNotes: string[] = [];
264
+ for (const p of resolvedPaths) {
265
+ for (const n of drainEncodingNotes(p)) {
266
+ if (collectedNotes.length < 6 && !collectedNotes.includes(n)) collectedNotes.push(n);
267
+ }
268
+ }
269
+ const suffix = notesToSuffix(collectedNotes);
270
+ return {
271
+ text: `Applied patch to ${results.length} file(s):\n${summaryLines.join("\n")}${suffix}`,
272
+ details: { files: results, ...(committedLabels.length > 0 ? { batchId } : {}) },
273
+ };
274
+ });
275
+ }
@@ -1,33 +1,17 @@
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";
1
+ // Pi `apply_patch` tool adapter wrapping the Pi-independent core (`./apply-patch-core`).
5
2
  import { Type, type Static } from "typebox";
6
3
  import { Box, Spacer, Text } from "@earendil-works/pi-tui";
7
4
  import { renderDiff, type AgentToolResult, type ToolDefinition } from "@earendil-works/pi-coding-agent";
5
+ import type { ReadScope } from "../operations";
8
6
  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";
7
+ executeApplyPatch as executeApplyPatchCore,
8
+ type ApplyPatchDetails,
9
+ type ApplyPatchFileResult,
10
+ } from "./apply-patch-core";
11
+ import { parseMultiFilePatch } from "./patch";
12
+ import { buildEditDiff } from "./tool";
13
+
14
+ export type { ApplyPatchDetails, ApplyPatchFileResult };
31
15
 
32
16
  export const applyPatchSchema = Type.Object({
33
17
  patch: Type.String(),
@@ -35,307 +19,13 @@ export const applyPatchSchema = Type.Object({
35
19
 
36
20
  export type ApplyPatchInput = Static<typeof applyPatchSchema>;
37
21
 
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
22
  export async function executeApplyPatch(
107
23
  cwd: string,
108
24
  patchText: string,
109
25
  scope: ReadScope,
110
26
  signal?: AbortSignal,
111
27
  ): 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
- });
28
+ return executeApplyPatchCore(cwd, patchText, scope, signal, (p, plan) => buildEditDiff(p, plan).diff);
339
29
  }
340
30
 
341
31
  export function createApplyPatchDefinition(cwd: string, scope: ReadScope): ToolDefinition<typeof applyPatchSchema, ApplyPatchDetails> {
@@ -4,9 +4,12 @@ export type EditErrorCode =
4
4
  | "CANCELLED" | "TEMP_WRITE_FAILED" | "VERIFY_FAILED" | "COMMIT_UNKNOWN";
5
5
 
6
6
  export class EditError extends Error {
7
- constructor(readonly code: EditErrorCode, message: string,
8
- readonly commitState: "not_applied" | "unknown" = "not_applied") {
7
+ readonly code: EditErrorCode;
8
+ readonly commitState: "not_applied" | "unknown";
9
+ constructor(code: EditErrorCode, message: string, commitState: "not_applied" | "unknown" = "not_applied") {
9
10
  super(`[${code}; ${commitState}] ${message}`);
11
+ this.code = code;
12
+ this.commitState = commitState;
10
13
  this.name = "EditError";
11
14
  }
12
15
  }