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.
Files changed (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/CHANGELOG.zh-CN.md +64 -0
  3. package/CONTRIBUTING.md +33 -0
  4. package/CONTRIBUTING.zh-CN.md +33 -0
  5. package/README.md +35 -6
  6. package/README.zh-CN.md +35 -6
  7. package/docs/ACCEPTANCE.md +30 -2
  8. package/docs/COMPATIBILITY.md +6 -1
  9. package/docs/CONFIG-GUIDE.md +4 -1
  10. package/docs/DESIGN-REVIEW.md +54 -0
  11. package/docs/EDIT-ENGINE.md +46 -0
  12. package/docs/EDITING-PLAN.md +16 -0
  13. package/docs/MCP-AND-MULTI-AGENT.md +111 -0
  14. package/docs/MODEL-EVAL.md +92 -0
  15. package/docs/PROGRESS.md +311 -0
  16. package/docs/RELEASING.md +4 -2
  17. package/docs/zh-CN/ACCEPTANCE.md +30 -2
  18. package/docs/zh-CN/COMPATIBILITY.md +6 -1
  19. package/docs/zh-CN/CONFIG-GUIDE.md +4 -1
  20. package/docs/zh-CN/DESIGN-REVIEW.md +54 -0
  21. package/docs/zh-CN/EDIT-ENGINE.md +46 -0
  22. package/docs/zh-CN/EDITING-PLAN.md +415 -0
  23. package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +111 -0
  24. package/docs/zh-CN/MODEL-EVAL.md +92 -0
  25. package/docs/zh-CN/PROGRESS.md +311 -0
  26. package/docs/zh-CN/RELEASING.md +4 -2
  27. package/docs/zh-CN/editing-plan-architecture.png +0 -0
  28. package/examples/all-utf8.jsonc +1 -0
  29. package/examples/embedded-c.jsonc +1 -0
  30. package/examples/legacy-java-web.jsonc +1 -0
  31. package/examples/mixed-repo.jsonc +1 -0
  32. package/package.json +14 -2
  33. package/prompts/charset-setup.md +3 -3
  34. package/schema/pi-charset.schema.json +118 -0
  35. package/skills/charset-rules/SKILL.md +8 -2
  36. package/src/config.ts +524 -185
  37. package/src/edit/apply-patch-core.ts +275 -0
  38. package/src/edit/apply-patch.ts +78 -0
  39. package/src/edit/diagnostics.ts +48 -0
  40. package/src/edit/hashline.ts +438 -0
  41. package/src/edit/patch.ts +655 -0
  42. package/src/edit/paths.ts +42 -0
  43. package/src/edit/plan.ts +107 -0
  44. package/src/edit/tool.ts +451 -0
  45. package/src/edit-preview.ts +48 -277
  46. package/src/encoding/classify.ts +235 -65
  47. package/src/encoding/common-scripts.ts +66 -0
  48. package/src/encoding/converter.ts +114 -16
  49. package/src/encoding/fast-codec.ts +469 -0
  50. package/src/encoding/file-stamp.ts +55 -0
  51. package/src/encoding/line-endings.ts +66 -73
  52. package/src/encoding/mime.ts +12 -43
  53. package/src/encoding/stream-transcode.ts +135 -30
  54. package/src/grep-core.ts +687 -0
  55. package/src/grep.ts +25 -463
  56. package/src/index.ts +458 -49
  57. package/src/journal.ts +459 -0
  58. package/src/maintenance.ts +375 -0
  59. package/src/mcp/server.ts +651 -0
  60. package/src/operations.ts +759 -127
  61. package/src/read-view.ts +924 -0
  62. package/src/resolve.ts +113 -101
  63. package/src/scaffold.ts +9 -4
  64. package/src/shell-guard.ts +617 -0
  65. package/src/shell.ts +85 -33
  66. package/src/sysnote.ts +4 -6
  67. package/src/version.ts +1 -1
  68. package/tools/charset-core.mjs +251 -0
  69. package/tools/pi-charset-cli.mjs +369 -0
  70. package/tools/pi-charset-mcp.mjs +103 -0
  71. package/tools/scan-encoding.mjs +30 -28
@@ -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
+ }
@@ -0,0 +1,78 @@
1
+ // Pi `apply_patch` tool adapter wrapping the Pi-independent core (`./apply-patch-core`).
2
+ import { Type, type Static } from "typebox";
3
+ import { Box, Spacer, Text } from "@earendil-works/pi-tui";
4
+ import { renderDiff, type AgentToolResult, type ToolDefinition } from "@earendil-works/pi-coding-agent";
5
+ import type { ReadScope } from "../operations";
6
+ import {
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 };
15
+
16
+ export const applyPatchSchema = Type.Object({
17
+ patch: Type.String(),
18
+ });
19
+
20
+ export type ApplyPatchInput = Static<typeof applyPatchSchema>;
21
+
22
+ export async function executeApplyPatch(
23
+ cwd: string,
24
+ patchText: string,
25
+ scope: ReadScope,
26
+ signal?: AbortSignal,
27
+ ): Promise<{ text: string; details: ApplyPatchDetails }> {
28
+ return executeApplyPatchCore(cwd, patchText, scope, signal, (p, plan) => buildEditDiff(p, plan).diff);
29
+ }
30
+
31
+ export function createApplyPatchDefinition(cwd: string, scope: ReadScope): ToolDefinition<typeof applyPatchSchema, ApplyPatchDetails> {
32
+ return {
33
+ name: "apply_patch",
34
+ label: "apply_patch (encoding aware)",
35
+ description:
36
+ "Atomic pre-validated multi-file patch: Codex (*** Begin Patch with Update/Hashline/Add/Delete/Move), Aider S/R, or unified diff.",
37
+ promptSnippet: "Atomic multi-file patch (Codex/Hashline/Aider/diff)",
38
+ parameters: applyPatchSchema,
39
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
40
+ renderShell: "self",
41
+ async execute(_toolCallId, params, signal, _onUpdate, ctx): Promise<AgentToolResult<ApplyPatchDetails>> {
42
+ const res = await executeApplyPatch(ctx?.cwd || cwd, params.patch, scope, signal);
43
+ return {
44
+ content: [{ type: "text", text: res.text }],
45
+ details: res.details,
46
+ };
47
+ },
48
+ renderCall(input, theme, context) {
49
+ const pad = "outputPad" in context && typeof context.outputPad === "number" ? context.outputPad : 1;
50
+ const box = new Box(pad, 1, (s) => theme.bg("toolPendingBg", s));
51
+ let targets = "(patch)";
52
+ if (typeof input?.patch === "string" && input.patch.trim()) {
53
+ try {
54
+ const ops = parseMultiFilePatch(input.patch);
55
+ targets = `${ops.length} file(s): ${ops.slice(0, 4).map((o) => o.path).join(", ")}${ops.length > 4 ? ", ..." : ""}`;
56
+ } catch { /* Streaming partial patch: wait for complete arguments. */ }
57
+ }
58
+ box.addChild(new Text(`${theme.fg("toolTitle", theme.bold("apply_patch"))} ${targets}`, 0, 0));
59
+ return box;
60
+ },
61
+ renderResult(result, _options, theme, context) {
62
+ const pad = "outputPad" in context && typeof context.outputPad === "number" ? context.outputPad : 1;
63
+ const box = new Box(pad, 0, (s) => theme.bg(context.isError ? "toolErrorBg" : "toolSuccessBg", s));
64
+ const summary = result.content.filter((p) => p.type === "text").map((p) => p.text).join("\n");
65
+ box.addChild(new Text(summary, 0, 0));
66
+ if (!context.isError && context.expanded && result.details?.files?.length) {
67
+ for (const f of result.details.files) {
68
+ if (!f.diff) continue;
69
+ box.addChild(new Spacer(1));
70
+ let rendered = f.diff;
71
+ try { rendered = renderDiff(f.diff, { filePath: f.movedTo ?? f.path }); } catch { /* Plain text fallback. */ }
72
+ box.addChild(new Text(`${theme.bold(f.movedTo ? `${f.path} -> ${f.movedTo}` : f.path)}\n${rendered}`, 0, 0));
73
+ }
74
+ }
75
+ return box;
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,48 @@
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
+ readonly code: EditErrorCode;
8
+ readonly commitState: "not_applied" | "unknown";
9
+ constructor(code: EditErrorCode, message: string, commitState: "not_applied" | "unknown" = "not_applied") {
10
+ super(`[${code}; ${commitState}] ${message}`);
11
+ this.code = code;
12
+ this.commitState = commitState;
13
+ this.name = "EditError";
14
+ }
15
+ }
16
+
17
+ export function lineAt(text: string, offset: number): number {
18
+ let count = 1;
19
+ for (let i = 0; i < offset; i++) if (text.charCodeAt(i) === 10) count++;
20
+ return count;
21
+ }
22
+
23
+ /** Hints are actual source lines, never replacement candidates selected by the tool. */
24
+ export function suggestLines(text: string, oldText: string): string {
25
+ const first = oldText.split(/\r?\n/).find((line) => line.trim())?.trim().slice(0, 120);
26
+ if (!first) return "";
27
+ const tokens = first.match(/[\p{L}\p{N}_]+/gu)?.filter((t) => t.length >= 2).slice(0, 8) ?? [];
28
+ const hints: { score: number; line: number; content: string }[] = [];
29
+ let start = 0;
30
+ let line = 1;
31
+ while (start < text.length) {
32
+ const next = text.indexOf("\n", start);
33
+ const raw = text.slice(start, next < 0 ? text.length : next);
34
+ const trimmed = raw.trim();
35
+ const score = trimmed.includes(first) ? 100 : tokens.reduce((sum, token) => sum + Number(trimmed.includes(token)), 0);
36
+ if (score && (hints.length < 3 || score > hints[2].score)) {
37
+ // JSON can use six bytes per code unit. Three 200-unit prefixes fit within 4 KiB.
38
+ hints.push({ score, line, content: raw.replace(/\r$/, "").slice(0, 200) });
39
+ hints.sort((a, b) => b.score - a.score || a.line - b.line);
40
+ if (hints.length > 3) hints.pop();
41
+ }
42
+ if (next < 0) break;
43
+ start = next + 1;
44
+ line++;
45
+ }
46
+ return hints.length ? "\nSource lines:\n" +
47
+ hints.map((hint) => `L${hint.line}: ${JSON.stringify(hint.content)}`).join("\n") : "";
48
+ }