pi-charset 0.1.6 → 0.1.8

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 (49) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/CHANGELOG.zh-CN.md +28 -0
  3. package/dist/config.js +943 -0
  4. package/dist/diagnostics/incidents.js +436 -0
  5. package/dist/edit/apply-patch-core.js +274 -0
  6. package/dist/edit/diagnostics.js +73 -0
  7. package/dist/edit/hashline.js +400 -0
  8. package/dist/edit/patch.js +634 -0
  9. package/dist/edit/paths.js +48 -0
  10. package/dist/edit/plan.js +90 -0
  11. package/dist/encoding/classify.js +430 -0
  12. package/dist/encoding/common-scripts.js +58 -0
  13. package/dist/encoding/converter.js +311 -0
  14. package/dist/encoding/fast-codec.js +476 -0
  15. package/dist/encoding/file-stamp.js +32 -0
  16. package/dist/encoding/line-endings.js +118 -0
  17. package/dist/encoding/mime.js +88 -0
  18. package/dist/encoding/stream-transcode.js +287 -0
  19. package/dist/faults.js +67 -0
  20. package/dist/grep-core.js +730 -0
  21. package/dist/journal.js +494 -0
  22. package/dist/maintenance.js +333 -0
  23. package/dist/mcp/server.js +959 -0
  24. package/dist/notify.js +60 -0
  25. package/dist/operations.js +1155 -0
  26. package/dist/path-key.js +10 -0
  27. package/dist/read-view.js +927 -0
  28. package/dist/resolve.js +325 -0
  29. package/dist/setup/adapters.js +524 -0
  30. package/dist/version.js +2 -0
  31. package/docs/MCP-AND-MULTI-AGENT.md +43 -20
  32. package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +43 -20
  33. package/package.json +14 -2
  34. package/src/diagnostics/incidents.ts +474 -0
  35. package/src/edit/apply-patch-core.ts +32 -3
  36. package/src/edit/diagnostics.ts +31 -0
  37. package/src/faults.ts +165 -0
  38. package/src/grep-core.ts +50 -8
  39. package/src/grep.ts +9 -1
  40. package/src/index.ts +8 -5
  41. package/src/journal.ts +167 -42
  42. package/src/mcp/server.ts +597 -179
  43. package/src/operations.ts +370 -100
  44. package/src/read-view.ts +111 -8
  45. package/src/setup/adapters.ts +613 -0
  46. package/src/shell-guard.ts +38 -1
  47. package/src/version.ts +1 -1
  48. package/tools/pi-charset-cli.mjs +664 -168
  49. package/tools/pi-charset-mcp.mjs +81 -42
@@ -0,0 +1,274 @@
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 { afterWrite, atomicReplace, canonicalKey, checkEditAbort, commitPlanLocked, loadSnapshot, prepareEditWithPlan, prepareNewFileWrite, verifyWritten, withPathLocks, } from "../operations.js";
6
+ import { allocateBatchId, autoCommitBatch, recordWrite } from "../journal.js";
7
+ import { drainEncodingNotes, notesToSuffix, pushEncodingNote } from "../notify.js";
8
+ import { EditError, lineAt } from "./diagnostics.js";
9
+ import { formatUpdatedHashlines, planHashlineEdits } from "./hashline.js";
10
+ import { planEdits } from "./plan.js";
11
+ import { parseMultiFilePatch, planHunks } from "./patch.js";
12
+ import { resolveEditPath } from "./paths.js";
13
+ /** Lightweight zero-dependency unified diff summary used when no Pi TUI diff renderer is supplied. */
14
+ export function compactRangeDiff(plan) {
15
+ if (!plan.changed || plan.ranges.length === 0)
16
+ return "";
17
+ const out = [];
18
+ for (const r of plan.ranges.slice(0, 12)) {
19
+ const startLine = lineAt(plan.before, r.start);
20
+ const oldLines = plan.before.slice(r.start, r.end).replace(/\r\n/g, "\n").split("\n");
21
+ const newLines = r.text.replace(/\r\n/g, "\n").split("\n");
22
+ out.push(`@@ -${startLine},${oldLines.length} +${startLine},${newLines.length} @@`);
23
+ for (const l of oldLines.slice(0, 12))
24
+ out.push(`-${l}`);
25
+ for (const l of newLines.slice(0, 12))
26
+ out.push(`+${l}`);
27
+ }
28
+ return out.join("\n");
29
+ }
30
+ async function assertPathAbsent(absPath) {
31
+ try {
32
+ await lstat(absPath);
33
+ throw new EditError("INVALID_INPUT", `Destination path already exists: ${absPath}`);
34
+ }
35
+ catch (e) {
36
+ if (e instanceof EditError)
37
+ throw e;
38
+ if (e?.code !== "ENOENT") {
39
+ throw new EditError("UNSUPPORTED_FILE", `Cannot inspect destination ${absPath}: ${String(e)}`);
40
+ }
41
+ }
42
+ }
43
+ function plannerForPatchOp(op) {
44
+ if (op.hashlines) {
45
+ return (before) => op.hashlines.length ? planHashlineEdits(before, op.hashlines) : { before, after: before, ranges: [], changed: false };
46
+ }
47
+ if (op.searchReplace)
48
+ return (before) => planEdits(before, op.searchReplace);
49
+ return (before) => planHunks(before, op.hunks);
50
+ }
51
+ /** Execute a multi-file patch with all-or-nothing pre-flight validation and deadlock-free path locking. */
52
+ export async function executeApplyPatch(cwd, patchText, scope, signal, formatDiff = (_p, plan) => compactRangeDiff(plan)) {
53
+ checkEditAbort(signal);
54
+ const rawOps = parseMultiFilePatch(patchText);
55
+ const resolvedPaths = [];
56
+ const resolvedOps = rawOps.map((op) => {
57
+ const absPath = resolveEditPath(op.path, cwd);
58
+ resolvedPaths.push(absPath);
59
+ if (op.type === "update" && op.moveTo) {
60
+ const destAbsPath = resolveEditPath(op.moveTo, cwd);
61
+ resolvedPaths.push(destAbsPath);
62
+ return { op, absPath, destAbsPath };
63
+ }
64
+ return { op, absPath, destAbsPath: undefined };
65
+ });
66
+ const seenTargets = new Set();
67
+ for (const { absPath, destAbsPath } of resolvedOps) {
68
+ const k = await canonicalKey(absPath);
69
+ if (seenTargets.has(k))
70
+ throw new EditError("INVALID_INPUT", `Patch targets the same path more than once: ${absPath}`);
71
+ seenTargets.add(k);
72
+ if (destAbsPath) {
73
+ const dk = await canonicalKey(destAbsPath);
74
+ if (seenTargets.has(dk))
75
+ throw new EditError("INVALID_INPUT", `Patch destination conflicts with another target in the same patch: ${destAbsPath}`);
76
+ seenTargets.add(dk);
77
+ }
78
+ }
79
+ const epoch = scope.epoch;
80
+ return withPathLocks(resolvedPaths, async () => {
81
+ checkEditAbort(signal);
82
+ if (scope.epoch !== epoch)
83
+ throw new EditError("STALE_PLAN", "Session changed before apply_patch execution.");
84
+ const staged = [];
85
+ const preflightErrors = [];
86
+ for (const { op, absPath, destAbsPath } of resolvedOps) {
87
+ checkEditAbort(signal);
88
+ try {
89
+ if (op.type === "add") {
90
+ await assertPathAbsent(absPath);
91
+ const prepared = await prepareNewFileWrite(absPath, op.content);
92
+ staged.push({ kind: "add", displayPath: op.path, absPath, key: await canonicalKey(absPath), prepared });
93
+ }
94
+ else if (op.type === "delete") {
95
+ const snapshot = await loadSnapshot(absPath, scope);
96
+ staged.push({ kind: "delete", displayPath: op.path, absPath: snapshot.absPath, snapshot });
97
+ }
98
+ else if (destAbsPath) {
99
+ await assertPathAbsent(destAbsPath);
100
+ const prepared = await prepareEditWithPlan(absPath, plannerForPatchOp(op), scope);
101
+ const diff = formatDiff(op.moveTo, prepared.plan);
102
+ staged.push({
103
+ kind: "move", displayPath: op.path, moveToDisplay: op.moveTo,
104
+ absPath: prepared.snapshot.absPath, destAbsPath, destKey: await canonicalKey(destAbsPath),
105
+ prepared, diff, isHashline: !!op.hashlines,
106
+ });
107
+ }
108
+ else {
109
+ const prepared = await prepareEditWithPlan(absPath, plannerForPatchOp(op), scope);
110
+ const diff = formatDiff(op.path, prepared.plan);
111
+ staged.push({ kind: "update", displayPath: op.path, absPath: prepared.snapshot.absPath, prepared, diff, isHashline: !!op.hashlines });
112
+ }
113
+ }
114
+ catch (err) {
115
+ preflightErrors.push({ path: op.path, error: err });
116
+ }
117
+ }
118
+ if (preflightErrors.length === 1)
119
+ throw preflightErrors[0].error;
120
+ if (preflightErrors.length > 1) {
121
+ const first = preflightErrors[0].error;
122
+ const code = first instanceof EditError ? first.code : "INVALID_INPUT";
123
+ const summary = preflightErrors.slice(0, 8).map(({ path: p, error }) => `- ${p}: ${error instanceof Error ? error.message : String(error)}`).join("\n");
124
+ const more = preflightErrors.length > 8 ? `\n... (${preflightErrors.length - 8} more file errors)` : "";
125
+ throw new EditError(code, `Pre-flight failed for ${preflightErrors.length} file(s); zero files modified:\n${summary}${more}`);
126
+ }
127
+ const batchId = allocateBatchId();
128
+ const results = [];
129
+ const summaryLines = [];
130
+ const committedLabels = [];
131
+ const autoCommitPaths = [];
132
+ let autoCommitRule = null;
133
+ const trackCommit = (rule, ...paths) => {
134
+ if (rule?.autoCommit) {
135
+ autoCommitRule ??= rule;
136
+ autoCommitPaths.push(...paths);
137
+ }
138
+ };
139
+ try {
140
+ for (const item of staged) {
141
+ checkEditAbort(signal);
142
+ if (item.kind === "update") {
143
+ await commitPlanLocked(item.prepared, scope, epoch, signal, undefined, true, batchId);
144
+ const action = item.prepared.plan.changed ? "updated" : "unchanged";
145
+ results.push({ action, path: item.displayPath, diff: item.diff });
146
+ if (action === "updated") {
147
+ committedLabels.push(`M ${item.displayPath}`);
148
+ trackCommit(item.prepared.snapshot.rule, item.absPath);
149
+ }
150
+ if (item.isHashline && item.prepared.plan.changed) {
151
+ const upd = formatUpdatedHashlines(item.prepared.plan, 8, 400);
152
+ const delta = upd.lineDelta ? ` (Δ${upd.lineDelta > 0 ? "+" : ""}${upd.lineDelta})` : "";
153
+ summaryLines.push(`M ${item.displayPath}${delta}${upd.lines.length ? "\n " + upd.lines.join("\n ") : ""}`);
154
+ }
155
+ else {
156
+ summaryLines.push(`${action === "updated" ? "M" : "="} ${item.displayPath}`);
157
+ }
158
+ }
159
+ else if (item.kind === "add") {
160
+ const { plan, g1, bytes, text, bomLen, provenLossless } = item.prepared;
161
+ for (const w of plan.warnings)
162
+ pushEncodingNote(item.absPath, w);
163
+ if (g1.note)
164
+ pushEncodingNote(item.absPath, g1.note);
165
+ await mkdir(path.dirname(item.absPath), { recursive: true });
166
+ await atomicReplace(item.absPath, bytes, null, undefined, signal);
167
+ await recordWrite(item.absPath, null, bytes, "add", batchId);
168
+ committedLabels.push(`A ${item.displayPath}`);
169
+ if (plan.rule && plan.rule.verifyWrite !== false) {
170
+ const problem = await verifyWritten(item.absPath, bytes, text, g1.encoding, plan.rule, bomLen, provenLossless);
171
+ if (problem)
172
+ throw new EditError("VERIFY_FAILED", `Post-write verification failed for ${item.displayPath}: ${problem}`, "unknown");
173
+ }
174
+ trackCommit(plan.rule, item.absPath);
175
+ afterWrite(item.absPath, bytes, scope, item.key, epoch);
176
+ results.push({ action: "added", path: item.displayPath });
177
+ summaryLines.push(`A ${item.displayPath}`);
178
+ }
179
+ else if (item.kind === "delete") {
180
+ const cur = await readFile(item.absPath).catch(() => null);
181
+ if (!cur?.equals(item.snapshot.raw))
182
+ throw new EditError("STALE_PLAN", `Target file changed before deletion: ${item.displayPath}`);
183
+ await unlink(item.absPath);
184
+ await recordWrite(item.absPath, item.snapshot.raw, null, "delete", batchId);
185
+ committedLabels.push(`D ${item.displayPath}`);
186
+ trackCommit(item.snapshot.rule, item.absPath);
187
+ afterWrite(item.absPath, null, scope, item.snapshot.key, epoch);
188
+ results.push({ action: "deleted", path: item.displayPath });
189
+ summaryLines.push(`D ${item.displayPath}`);
190
+ }
191
+ else {
192
+ const { snapshot, bytes } = item.prepared;
193
+ const curSrc = await readFile(item.absPath).catch(() => null);
194
+ if (!curSrc?.equals(snapshot.raw))
195
+ throw new EditError("STALE_PLAN", `Source file changed before move: ${item.displayPath}`);
196
+ await mkdir(path.dirname(item.destAbsPath), { recursive: true });
197
+ await atomicReplace(item.destAbsPath, bytes, null, undefined, signal);
198
+ if (snapshot.rule.verifyWrite !== false) {
199
+ const problem = await verifyWritten(item.destAbsPath, bytes, item.prepared.plan.after, snapshot.encoding, snapshot.rule, snapshot.bomLength, true);
200
+ if (problem)
201
+ throw new EditError("VERIFY_FAILED", `Post-write verification failed for moved destination ${item.moveToDisplay}: ${problem}`, "unknown");
202
+ }
203
+ else {
204
+ const written = await readFile(item.destAbsPath).catch(() => null);
205
+ if (!written?.equals(bytes))
206
+ throw new EditError("VERIFY_FAILED", `Post-write verification failed for moved destination ${item.moveToDisplay}.`, "unknown");
207
+ }
208
+ await recordWrite(item.destAbsPath, null, bytes, "add", batchId);
209
+ afterWrite(item.destAbsPath, bytes, scope, item.destKey, epoch);
210
+ const destLabelIdx = committedLabels.length;
211
+ committedLabels.push(`A ${item.moveToDisplay}`);
212
+ // Re-verify source identity and exact bytes immediately before unlinking so an external edit
213
+ // that landed while writing the destination is never silently deleted.
214
+ const srcStatBeforeUnlink = await lstat(item.absPath).catch(() => null);
215
+ const srcBytesBeforeUnlink = srcStatBeforeUnlink &&
216
+ srcStatBeforeUnlink.isFile() &&
217
+ !srcStatBeforeUnlink.isSymbolicLink() &&
218
+ srcStatBeforeUnlink.nlink === 1 &&
219
+ srcStatBeforeUnlink.dev === snapshot.identity.dev &&
220
+ srcStatBeforeUnlink.ino === snapshot.identity.ino
221
+ ? await readFile(item.absPath).catch(() => null)
222
+ : null;
223
+ if (!srcBytesBeforeUnlink?.equals(snapshot.raw)) {
224
+ throw new EditError("STALE_PLAN", `Source file changed externally during move; preserved modified source ${item.displayPath} without deleting it.`, "unknown");
225
+ }
226
+ await unlink(item.absPath);
227
+ await recordWrite(item.absPath, snapshot.raw, null, "delete", batchId);
228
+ committedLabels[destLabelIdx] = `R ${item.displayPath} -> ${item.moveToDisplay}`;
229
+ trackCommit(snapshot.rule, item.absPath, item.destAbsPath);
230
+ afterWrite(item.absPath, null, scope, snapshot.key, epoch);
231
+ results.push({ action: "moved", path: item.displayPath, movedTo: item.moveToDisplay, diff: item.diff });
232
+ if (item.isHashline && item.prepared.plan.changed) {
233
+ const upd = formatUpdatedHashlines(item.prepared.plan, 8, 400);
234
+ const delta = upd.lineDelta ? ` (Δ${upd.lineDelta > 0 ? "+" : ""}${upd.lineDelta})` : "";
235
+ summaryLines.push(`R ${item.displayPath} -> ${item.moveToDisplay}${delta}${upd.lines.length ? "\n " + upd.lines.join("\n ") : ""}`);
236
+ }
237
+ else {
238
+ summaryLines.push(`R ${item.displayPath} -> ${item.moveToDisplay}`);
239
+ }
240
+ }
241
+ }
242
+ }
243
+ catch (error) {
244
+ if (committedLabels.length > 0) {
245
+ const baseMsg = error instanceof Error ? error.message : String(error);
246
+ const code = error instanceof EditError ? error.code : "COMMIT_UNKNOWN";
247
+ throw new EditError(code, `Partial commit (${committedLabels.join(", ")} already written; use /charset-undo b${batchId} to revert): ${baseMsg}`, "unknown");
248
+ }
249
+ throw error;
250
+ }
251
+ let commitRes = { committed: false };
252
+ if (autoCommitPaths.length > 0 && autoCommitRule) {
253
+ commitRes = await autoCommitBatch(autoCommitPaths, autoCommitRule, "patch", (note) => pushEncodingNote(autoCommitPaths[0], note));
254
+ }
255
+ const collectedNotes = [];
256
+ for (const p of resolvedPaths) {
257
+ for (const n of drainEncodingNotes(p)) {
258
+ if (collectedNotes.length < 6 && !collectedNotes.includes(n))
259
+ collectedNotes.push(n);
260
+ }
261
+ }
262
+ const suffix = notesToSuffix(collectedNotes);
263
+ return {
264
+ text: `Applied patch to ${results.length} file(s):\n${summaryLines.join("\n")}${suffix}`,
265
+ details: {
266
+ files: results,
267
+ ...(committedLabels.length > 0 ? { batchId } : {}),
268
+ committed: commitRes.committed,
269
+ ...(commitRes.skippedReason ? { commitSkippedReason: commitRes.skippedReason } : {}),
270
+ ...(commitRes.error ? { commitError: commitRes.error } : {}),
271
+ },
272
+ };
273
+ });
274
+ }
@@ -0,0 +1,73 @@
1
+ const EDIT_ERROR_MAP = {
2
+ INVALID_INPUT: { code: "INVALID_INPUT", category: "input", phase: "validate", retryable: false, actionHint: "Fix the edit input parameters and retry." },
3
+ NOT_FOUND: { code: "NOT_FOUND", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read the file with charset_read to confirm target text or path." },
4
+ AMBIGUOUS_MATCH: { code: "CONFLICT", category: "conflict", phase: "validate", retryable: true, actionHint: "Provide more context or use hashlines anchors for an exact match." },
5
+ OVERLAPPING_EDITS: { code: "INVALID_INPUT", category: "input", phase: "validate", retryable: false, actionHint: "Make edit ranges disjoint and retry." },
6
+ HASH_MISMATCH: { code: "STALE_VERSION", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read the file with hashlines=true and use the updated anchors." },
7
+ UNSUPPORTED_FILE: { code: "UNSUPPORTED_FILE", category: "policy", phase: "detect", retryable: false, actionHint: "Inspect the file with charset_check; symlinks, hardlinks, read-only, and binary files are refused." },
8
+ UNENCODABLE: { code: "UNMAPPABLE", category: "policy", phase: "encode", retryable: false, actionHint: "Replace unmappable characters or convert the file encoding explicitly via charset_fix." },
9
+ AMBIGUOUS_ENCODING: { code: "AMBIGUOUS_ENCODING", category: "policy", phase: "detect", retryable: false, actionHint: "Inspect with charset_check and declare the intended encoding before non-ASCII writes." },
10
+ STALE_READ: { code: "STALE_VERSION", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read using charset_read, then rebuild the edit with the latest version." },
11
+ STALE_PLAN: { code: "CONFLICT", category: "conflict", phase: "commit", retryable: true, actionHint: "Re-read using charset_read and retry the edit against the current file state." },
12
+ CANCELLED: { code: "CANCELLED", category: "io", phase: "commit", retryable: true, actionHint: "Retry if the cancellation was unintentional." },
13
+ TEMP_WRITE_FAILED: { code: "WRITE_FAILED", category: "io", phase: "commit", retryable: true, actionHint: "Check directory permissions and free disk space, then retry." },
14
+ VERIFY_FAILED: { code: "WRITE_VERIFY_FAILED", category: "engine", phase: "verify", retryable: false, actionHint: "Re-read the file to inspect on-disk state before retrying; use charset_fix(action='undo') if needed." },
15
+ COMMIT_UNKNOWN: { code: "WRITE_FAILED", category: "io", phase: "commit", retryable: false, actionHint: "Re-read the file to confirm on-disk state before retrying." },
16
+ };
17
+ export class EditError extends Error {
18
+ code;
19
+ commitState;
20
+ constructor(code, message, commitState = "not_applied") {
21
+ super(`[${code}; ${commitState}] ${message}`);
22
+ this.code = code;
23
+ this.commitState = commitState;
24
+ this.name = "EditError";
25
+ }
26
+ toFaultMetadata() {
27
+ const base = EDIT_ERROR_MAP[this.code];
28
+ const outcome = this.commitState === "not_applied" ? "not_applied" : "uncertain";
29
+ return {
30
+ ...base,
31
+ outcome,
32
+ applied: false,
33
+ verified: false,
34
+ committed: false,
35
+ };
36
+ }
37
+ }
38
+ export function lineAt(text, offset) {
39
+ let count = 1;
40
+ for (let i = 0; i < offset; i++)
41
+ if (text.charCodeAt(i) === 10)
42
+ count++;
43
+ return count;
44
+ }
45
+ /** Hints are actual source lines, never replacement candidates selected by the tool. */
46
+ export function suggestLines(text, oldText) {
47
+ const first = oldText.split(/\r?\n/).find((line) => line.trim())?.trim().slice(0, 120);
48
+ if (!first)
49
+ return "";
50
+ const tokens = first.match(/[\p{L}\p{N}_]+/gu)?.filter((t) => t.length >= 2).slice(0, 8) ?? [];
51
+ const hints = [];
52
+ let start = 0;
53
+ let line = 1;
54
+ while (start < text.length) {
55
+ const next = text.indexOf("\n", start);
56
+ const raw = text.slice(start, next < 0 ? text.length : next);
57
+ const trimmed = raw.trim();
58
+ const score = trimmed.includes(first) ? 100 : tokens.reduce((sum, token) => sum + Number(trimmed.includes(token)), 0);
59
+ if (score && (hints.length < 3 || score > hints[2].score)) {
60
+ // JSON can use six bytes per code unit. Three 200-unit prefixes fit within 4 KiB.
61
+ hints.push({ score, line, content: raw.replace(/\r$/, "").slice(0, 200) });
62
+ hints.sort((a, b) => b.score - a.score || a.line - b.line);
63
+ if (hints.length > 3)
64
+ hints.pop();
65
+ }
66
+ if (next < 0)
67
+ break;
68
+ start = next + 1;
69
+ line++;
70
+ }
71
+ return hints.length ? "\nSource lines:\n" +
72
+ hints.map((hint) => `L${hint.line}: ${JSON.stringify(hint.content)}`).join("\n") : "";
73
+ }