pi-charset 0.1.7 → 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.
@@ -0,0 +1,474 @@
1
+ // Privacy-first local incident recorder integrated into pi-charset's shared core.
2
+ // Zero network calls, zero raw exception text, zero source code, zero paths, zero credentials.
3
+ // Uses Node built-ins only; only call with structured, trusted internal metadata from typed faults.
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { promises as fs } from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { PLUGIN_VERSION } from "../version";
9
+
10
+ const SCHEMA = 1;
11
+
12
+ export type ReportableIncidentCode =
13
+ | "WRITE_VERIFY_FAILED"
14
+ | "ROLLBACK_FAILED"
15
+ | "BYTE_INVARIANT_FAILED"
16
+ | "MCP_PROTOCOL_ERROR"
17
+ | "CLIENT_STARTUP_FAILED"
18
+ | "TOOL_BYPASS_DETECTED"
19
+ | "LOCK_INVARIANT_FAILED"
20
+ | "GIT_INDEX_INVARIANT_FAILED"
21
+ | "SEARCH_ENGINE_FAILED"
22
+ | "INTERNAL";
23
+
24
+ const CODES: Readonly<Record<ReportableIncidentCode, readonly [string, string]>> = Object.freeze({
25
+ WRITE_VERIFY_FAILED: ["engine", "Verify rollback and reproduce using a synthetic encoded fixture."],
26
+ ROLLBACK_FAILED: ["critical", "Stop further writes; inspect local recovery journal."],
27
+ BYTE_INVARIANT_FAILED: ["critical", "Stop further writes; compare synthetic byte-preservation fixture."],
28
+ MCP_PROTOCOL_ERROR: ["compatibility", "Reproduce initialize, tools/list and tools/call with a synthetic client."],
29
+ CLIENT_STARTUP_FAILED: ["compatibility", "Check installed package entrypoint, runtime and stdio handshake."],
30
+ TOOL_BYPASS_DETECTED: ["compatibility", "Check client rules and hooks; inspect local Git diff."],
31
+ LOCK_INVARIANT_FAILED: ["engine", "Reproduce with separate processes and concurrent writes."],
32
+ GIT_INDEX_INVARIANT_FAILED: ["critical", "Reproduce in a temporary repository with staged changes."],
33
+ SEARCH_ENGINE_FAILED: ["compatibility", "Reproduce with synthetic legacy-encoded files and ripgrep."],
34
+ INTERNAL: ["engine", "Reproduce the failed operation with a minimal synthetic fixture."],
35
+ });
36
+
37
+ const EXPECTED_REJECTIONS = new Set([
38
+ "INVALID_INPUT",
39
+ "UNMAPPABLE",
40
+ "UNKNOWN_ENCODING",
41
+ "AMBIGUOUS_ENCODING",
42
+ "MIXED_EOL",
43
+ "STALE_VERSION",
44
+ "STALE_READ",
45
+ "CONFLICT",
46
+ "CANCELLED",
47
+ "PERMISSION_DENIED",
48
+ "NOT_FOUND",
49
+ "BINARY_FILE",
50
+ "UNSUPPORTED_FILE",
51
+ "LOCK_BUSY",
52
+ ]);
53
+
54
+ const OPS = [
55
+ "read", "write", "edit", "apply_patch", "grep", "check", "fix", "undo",
56
+ "setup", "initialize", "tools_list", "hook", "unknown",
57
+ ] as const;
58
+ const CLIENTS = [
59
+ "pi", "codex", "agy", "antigravity-ide", "antigravity-app",
60
+ "claude", "cursor", "windsurf", "generic", "unknown",
61
+ ] as const;
62
+ const ENCODINGS = [
63
+ "ASCII", "UTF-8", "UTF-16LE", "UTF-16BE", "GBK", "GB18030",
64
+ "BIG5", "SHIFT_JIS", "EUC-KR", "EUC-JP", "ISO-8859-1", "UNKNOWN", "unknown",
65
+ ] as const;
66
+ const PHASES = [
67
+ "startup", "detect", "decode", "validate", "encode", "commit",
68
+ "verify", "rollback", "transport", "search", "policy", "unknown",
69
+ ] as const;
70
+ const OUTCOMES = ["not_applied", "rolled_back", "applied_verified", "uncertain", "unknown"] as const;
71
+ const PLATFORMS = ["win32", "linux", "darwin", "unknown"] as const;
72
+ const ARCHS = ["x64", "arm64", "ia32", "unknown"] as const;
73
+ const EOLS = ["LF", "CRLF", "CR", "MIXED", "NONE", "unknown"] as const;
74
+ const SIZE_BUCKETS = ["lt4KiB", "4-64KiB", "64KiB-1MiB", "1-10MiB", "gte10MiB", "unknown"] as const;
75
+
76
+ function enumValue<T extends readonly string[]>(v: unknown, allowed: T): T[number] {
77
+ return typeof v === "string" && (allowed as readonly string[]).includes(v) ? (v as T[number]) : "unknown";
78
+ }
79
+
80
+ function sanitizeVersion(v: unknown): string {
81
+ return typeof v === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[0-9A-Za-z.-]{1,24})?$/.test(v) ? v : "unknown";
82
+ }
83
+
84
+ function dayString(date: Date): string {
85
+ return date.toISOString().slice(0, 10);
86
+ }
87
+
88
+ function bucketSize(v: unknown): (typeof SIZE_BUCKETS)[number] {
89
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) return "unknown";
90
+ if (v < 4096) return "lt4KiB";
91
+ if (v < 65536) return "4-64KiB";
92
+ if (v < 1048576) return "64KiB-1MiB";
93
+ if (v < 10485760) return "1-10MiB";
94
+ return "gte10MiB";
95
+ }
96
+
97
+ export interface IncidentRuntime {
98
+ readonly client?: string;
99
+ readonly packageVersion?: string;
100
+ readonly platform?: string;
101
+ readonly arch?: string;
102
+ }
103
+
104
+ export interface IncidentInput {
105
+ readonly code: string;
106
+ readonly operation?: string;
107
+ readonly phase?: string;
108
+ readonly outcome?: string;
109
+ readonly encoding?: string;
110
+ readonly eol?: string;
111
+ readonly fileBytes?: number;
112
+ }
113
+
114
+ export interface NormalizedIncident {
115
+ readonly schema: 1;
116
+ readonly code: ReportableIncidentCode;
117
+ readonly category: string;
118
+ readonly operation: string;
119
+ readonly phase: string;
120
+ readonly outcome: string;
121
+ readonly client: string;
122
+ readonly packageVersion: string;
123
+ readonly platform: string;
124
+ readonly arch: string;
125
+ readonly nodeMajor: number;
126
+ readonly encoding: string;
127
+ readonly eol: string;
128
+ readonly sizeBucket: string;
129
+ readonly fingerprint: string;
130
+ }
131
+
132
+ function fingerprintFields(fields: Omit<NormalizedIncident, "fingerprint">): string {
133
+ return createHash("sha256").update(JSON.stringify(fields)).digest("hex").slice(0, 32);
134
+ }
135
+
136
+ export function normalizeIncident(input: IncidentInput | Record<string, unknown> = {}, runtime: IncidentRuntime = {}): NormalizedIncident | null {
137
+ if (!input || typeof input !== "object") return null;
138
+ const code = (input as { code?: unknown }).code;
139
+ if (typeof code !== "string" || EXPECTED_REJECTIONS.has(code) || !Object.hasOwn(CODES, code)) return null;
140
+ const typedCode = code as ReportableIncidentCode;
141
+ const fields: Omit<NormalizedIncident, "fingerprint"> = {
142
+ schema: SCHEMA,
143
+ code: typedCode,
144
+ category: CODES[typedCode][0],
145
+ operation: enumValue((input as IncidentInput).operation, OPS),
146
+ phase: enumValue((input as IncidentInput).phase, PHASES),
147
+ outcome: enumValue((input as IncidentInput).outcome, OUTCOMES),
148
+ client: enumValue(runtime.client, CLIENTS),
149
+ packageVersion: sanitizeVersion(runtime.packageVersion ?? PLUGIN_VERSION),
150
+ platform: enumValue(runtime.platform ?? process.platform, PLATFORMS),
151
+ arch: enumValue(runtime.arch ?? process.arch, ARCHS),
152
+ nodeMajor: Math.min(99, Math.max(0, Number(process.versions.node.split(".")[0]) || 0)),
153
+ encoding: enumValue(
154
+ typeof (input as IncidentInput).encoding === "string" ? (input as IncidentInput).encoding!.toUpperCase() : "unknown",
155
+ ENCODINGS,
156
+ ),
157
+ eol: enumValue((input as IncidentInput).eol, EOLS),
158
+ sizeBucket: bucketSize((input as IncidentInput).fileBytes),
159
+ };
160
+ return Object.freeze({ ...fields, fingerprint: fingerprintFields(fields) });
161
+ }
162
+
163
+ export function diagnosticsStateRoot(): string {
164
+ if (process.env.PI_CHARSET_DIAGNOSTICS_DIR?.trim()) {
165
+ return path.resolve(process.env.PI_CHARSET_DIAGNOSTICS_DIR.trim());
166
+ }
167
+ if (process.platform === "win32") {
168
+ return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"), "pi-charset", "diagnostics-v1");
169
+ }
170
+ if (process.platform === "darwin") {
171
+ return path.join(os.homedir(), "Library", "Application Support", "pi-charset", "diagnostics-v1");
172
+ }
173
+ return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"), "pi-charset", "diagnostics-v1");
174
+ }
175
+
176
+ /** Respect user-level opt-out (env var only; never overridden by project .pi-charset.json or model prompts). */
177
+ export function isDiagnosticsEnabledByEnv(): boolean {
178
+ const v = (process.env.PI_CHARSET_DIAGNOSTICS ?? "").trim().toLowerCase();
179
+ if (v === "0" || v === "false" || v === "off" || v === "no") return false;
180
+ return true;
181
+ }
182
+
183
+ const isDayDir = (v: string) => /^\d{4}-\d{2}-\d{2}$/.test(v);
184
+ const isSlotFile = (v: string) => /^slot-\d{3}\.json$/.test(v);
185
+ const isTempFile = (v: string) => /^\.tmp-[0-9a-f]{24}$/.test(v);
186
+
187
+ async function safeDir(dir: string): Promise<void> {
188
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
189
+ const s = await fs.lstat(dir);
190
+ if (!s.isDirectory() || s.isSymbolicLink()) throw new Error("unsafe diagnostic directory");
191
+ }
192
+
193
+ function validatePersisted(v: unknown): NormalizedIncident | null {
194
+ if (!v || typeof v !== "object") return null;
195
+ const obj = v as Record<string, unknown>;
196
+ if (obj.schema !== SCHEMA || typeof obj.code !== "string" || !Object.hasOwn(CODES, obj.code)) return null;
197
+ const typedCode = obj.code as ReportableIncidentCode;
198
+ const fields: Omit<NormalizedIncident, "fingerprint"> = {
199
+ schema: SCHEMA,
200
+ code: typedCode,
201
+ category: CODES[typedCode][0],
202
+ operation: enumValue(obj.operation, OPS),
203
+ phase: enumValue(obj.phase, PHASES),
204
+ outcome: enumValue(obj.outcome, OUTCOMES),
205
+ client: enumValue(obj.client, CLIENTS),
206
+ packageVersion: sanitizeVersion(obj.packageVersion),
207
+ platform: enumValue(obj.platform, PLATFORMS),
208
+ arch: enumValue(obj.arch, ARCHS),
209
+ nodeMajor: typeof obj.nodeMajor === "number" && Number.isInteger(obj.nodeMajor) && obj.nodeMajor >= 0 && obj.nodeMajor <= 99 ? obj.nodeMajor : 0,
210
+ encoding: enumValue(obj.encoding, ENCODINGS),
211
+ eol: enumValue(obj.eol, EOLS),
212
+ sizeBucket: enumValue(obj.sizeBucket, SIZE_BUCKETS),
213
+ };
214
+ const fingerprint = fingerprintFields(fields);
215
+ if (obj.fingerprint !== fingerprint) return null;
216
+ return { ...fields, fingerprint };
217
+ }
218
+
219
+ async function readRecord(file: string): Promise<NormalizedIncident | null> {
220
+ try {
221
+ const st = await fs.lstat(file);
222
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 4096) return null;
223
+ return validatePersisted(JSON.parse(await fs.readFile(file, "utf8")));
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
228
+
229
+ export function issueDraft(report: NormalizedIncident | Record<string, unknown>): { title: string; body: string } {
230
+ const r = validatePersisted(report);
231
+ if (!r) throw new Error("Invalid incident report");
232
+ return {
233
+ title: `[${r.code}] ${r.operation} / ${r.client} / ${r.platform}`,
234
+ body:
235
+ `## Sanitized diagnostic\n\n` +
236
+ `Fingerprint: \`${r.fingerprint}\`\n\n` +
237
+ `\`\`\`json\n${JSON.stringify(r, null, 2)}\n\`\`\`\n\n` +
238
+ `## Suggested reproduction\n\n` +
239
+ `${CODES[r.code][1]}\n\n` +
240
+ `No project files, file paths, raw error messages, environment variables, credentials, or prompts are included. This is a diagnostic signal, not proof of root cause.\n`,
241
+ };
242
+ }
243
+
244
+ export function buildIssueUrl(report: NormalizedIncident | Record<string, unknown>, repo = "ethan-blue/pi-charset"): string {
245
+ const draft = issueDraft(report);
246
+ const url = new URL(`https://github.com/${repo}/issues/new`);
247
+ url.searchParams.set("title", draft.title);
248
+ url.searchParams.set("body", draft.body);
249
+ return url.href;
250
+ }
251
+
252
+ export interface IncidentRecorderOptions {
253
+ readonly root?: string;
254
+ readonly enabled?: boolean;
255
+ readonly runtime?: IncidentRuntime;
256
+ readonly slotsPerDay?: number;
257
+ readonly retentionDays?: number;
258
+ readonly maxPending?: number;
259
+ readonly clock?: () => Date;
260
+ }
261
+
262
+ export interface RecordOutcome {
263
+ readonly status: "disabled" | "ignored" | "duplicate" | "queue_full" | "queued" | "unavailable";
264
+ readonly fingerprint?: string;
265
+ }
266
+
267
+ export class IncidentRecorder {
268
+ readonly root: string;
269
+ readonly enabled: boolean;
270
+ readonly runtime: IncidentRuntime;
271
+ readonly slots: number;
272
+ readonly retention: number;
273
+ readonly maxPending: number;
274
+ readonly clock: () => Date;
275
+
276
+ #pending: { date: string; event: NormalizedIncident; key: string }[] = [];
277
+ #drain: Promise<void> | null = null;
278
+ #seen = new Set<string>();
279
+ #lastPrune = "";
280
+
281
+ constructor(opts: IncidentRecorderOptions = {}) {
282
+ this.root = path.resolve(opts.root ?? diagnosticsStateRoot());
283
+ this.enabled = opts.enabled !== undefined ? opts.enabled === true : isDiagnosticsEnabledByEnv();
284
+ this.runtime = { packageVersion: PLUGIN_VERSION, ...opts.runtime };
285
+ this.slots = Math.max(1, Math.min(256, Math.floor(opts.slotsPerDay ?? 64) || 64));
286
+ this.retention = Math.max(1, Math.min(30, Math.floor(opts.retentionDays ?? 14) || 14));
287
+ this.maxPending = Math.max(1, Math.min(128, Math.floor(opts.maxPending ?? 32) || 32));
288
+ this.clock = opts.clock ?? (() => new Date());
289
+ }
290
+
291
+ /** Fire-and-forget on reportable failure only; bounded memory, zero stdout logging, never throws. */
292
+ record(input: IncidentInput | Record<string, unknown>): RecordOutcome {
293
+ try {
294
+ if (!this.enabled) return { status: "disabled" };
295
+ const event = normalizeIncident(input, this.runtime);
296
+ if (!event) return { status: "ignored" };
297
+ const date = dayString(this.clock());
298
+ const key = `${date}:${event.fingerprint}`;
299
+ if (this.#seen.has(key)) return { status: "duplicate", fingerprint: event.fingerprint };
300
+ if (this.#pending.length >= this.maxPending) return { status: "queue_full" };
301
+ this.#seen.add(key);
302
+ if (this.#seen.size > 512) {
303
+ this.#seen.clear();
304
+ this.#seen.add(key);
305
+ }
306
+ this.#pending.push({ date, event, key });
307
+ this.#startDrain();
308
+ return { status: "queued", fingerprint: event.fingerprint };
309
+ } catch {
310
+ return { status: "unavailable" };
311
+ }
312
+ }
313
+
314
+ #startDrain(): void {
315
+ if (this.#drain) return;
316
+ this.#drain = this.#run().finally(() => {
317
+ this.#drain = null;
318
+ if (this.#pending.length) this.#startDrain();
319
+ });
320
+ }
321
+
322
+ async #publishSlot(temp: string, dest: string, payload: string): Promise<"published" | "exists"> {
323
+ try {
324
+ await fs.link(temp, dest);
325
+ return "published";
326
+ } catch (error) {
327
+ const code = (error as NodeJS.ErrnoException)?.code;
328
+ if (code === "EEXIST") return "exists";
329
+ // Safe fallback for filesystems without hard-link support (e.g. FAT32/exFAT/network mounts).
330
+ if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV" || code === "EACCES" || code === "ENOSYS") {
331
+ try {
332
+ await fs.writeFile(dest, payload, { flag: "wx", mode: 0o600 });
333
+ return "published";
334
+ } catch (wxErr) {
335
+ if ((wxErr as NodeJS.ErrnoException)?.code === "EEXIST") return "exists";
336
+ throw wxErr;
337
+ }
338
+ }
339
+ throw error;
340
+ }
341
+ }
342
+
343
+ async #run(): Promise<void> {
344
+ while (this.#pending.length) {
345
+ const item = this.#pending.shift()!;
346
+ const { date, event, key } = item;
347
+ try {
348
+ await safeDir(this.root);
349
+ if (this.#lastPrune !== date) {
350
+ await this.prune();
351
+ this.#lastPrune = date;
352
+ }
353
+ const dir = path.join(this.root, date);
354
+ await safeDir(dir);
355
+ const payload = JSON.stringify(event) + "\n";
356
+ const temp = path.join(dir, `.tmp-${randomBytes(12).toString("hex")}`);
357
+ try {
358
+ await fs.writeFile(temp, payload, { flag: "wx", mode: 0o600 });
359
+ const start = parseInt(event.fingerprint.slice(0, 8), 16) % this.slots;
360
+ for (let i = 0; i < this.slots; i++) {
361
+ const dest = path.join(dir, `slot-${String((start + i) % this.slots).padStart(3, "0")}.json`);
362
+ const pub = await this.#publishSlot(temp, dest, payload);
363
+ if (pub === "published") break;
364
+ const existing = await readRecord(dest);
365
+ if (existing?.fingerprint === event.fingerprint) break;
366
+ }
367
+ } finally {
368
+ await fs.unlink(temp).catch(() => undefined);
369
+ }
370
+ } catch {
371
+ this.#seen.delete(key);
372
+ // Diagnostic I/O must never alter or block tool results.
373
+ }
374
+ }
375
+ }
376
+
377
+ async flush(timeoutMs = 1500): Promise<void> {
378
+ const waitAll = async () => {
379
+ while (this.#drain) await this.#drain;
380
+ };
381
+ if (timeoutMs <= 0) {
382
+ await waitAll();
383
+ return;
384
+ }
385
+ await Promise.race([
386
+ waitAll(),
387
+ new Promise<void>((resolve) => {
388
+ const t = setTimeout(resolve, timeoutMs);
389
+ t.unref?.();
390
+ }),
391
+ ]);
392
+ }
393
+
394
+ async prune(): Promise<void> {
395
+ const cutoff = new Date(this.clock().getTime() - (this.retention - 1) * 86400000).toISOString().slice(0, 10);
396
+ let dirs;
397
+ try { dirs = await fs.readdir(this.root, { withFileTypes: true }); } catch { return; }
398
+ for (const d of dirs) {
399
+ if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name)) continue;
400
+ const expired = d.name < cutoff;
401
+ const dir = path.join(this.root, d.name);
402
+ try {
403
+ for (const f of await fs.readdir(dir, { withFileTypes: true })) {
404
+ if (!f.isFile() || f.isSymbolicLink() || !(isSlotFile(f.name) || isTempFile(f.name))) continue;
405
+ const full = path.join(dir, f.name);
406
+ if (
407
+ (expired && isSlotFile(f.name)) ||
408
+ (isTempFile(f.name) && this.clock().getTime() - (await fs.stat(full)).mtimeMs > 86400000)
409
+ ) {
410
+ await fs.unlink(full).catch(() => undefined);
411
+ }
412
+ }
413
+ if (expired) await fs.rmdir(dir).catch(() => undefined);
414
+ } catch { /* Concurrent process may prune first. */ }
415
+ }
416
+ }
417
+
418
+ async clear(): Promise<number> {
419
+ await this.flush();
420
+ this.#seen.clear();
421
+ let removed = 0;
422
+ let dirs;
423
+ try { dirs = await fs.readdir(this.root, { withFileTypes: true }); } catch { return 0; }
424
+ for (const d of dirs) {
425
+ if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name)) continue;
426
+ const dir = path.join(this.root, d.name);
427
+ try {
428
+ for (const f of await fs.readdir(dir, { withFileTypes: true })) {
429
+ if (!f.isFile() || f.isSymbolicLink() || !(isSlotFile(f.name) || isTempFile(f.name))) continue;
430
+ await fs.unlink(path.join(dir, f.name)).catch(() => undefined);
431
+ if (isSlotFile(f.name)) removed++;
432
+ }
433
+ await fs.rmdir(dir).catch(() => undefined);
434
+ } catch { /* ignore */ }
435
+ }
436
+ return removed;
437
+ }
438
+
439
+ async list(): Promise<{ date: string; report: NormalizedIncident }[]> {
440
+ await this.flush();
441
+ const out: { date: string; report: NormalizedIncident }[] = [];
442
+ let dirs;
443
+ try { dirs = await fs.readdir(this.root, { withFileTypes: true }); } catch { return out; }
444
+ for (const d of dirs) {
445
+ if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name)) continue;
446
+ const dir = path.join(this.root, d.name);
447
+ let files;
448
+ try { files = await fs.readdir(dir, { withFileTypes: true }); } catch { continue; }
449
+ for (const f of files) {
450
+ if (!f.isFile() || !isSlotFile(f.name)) continue;
451
+ const report = await readRecord(path.join(dir, f.name));
452
+ if (report) out.push({ date: d.name, report });
453
+ }
454
+ }
455
+ return out.sort((a, b) => b.date.localeCompare(a.date) || a.report.fingerprint.localeCompare(b.report.fingerprint));
456
+ }
457
+ }
458
+
459
+ let singletonRecorder: IncidentRecorder | null = null;
460
+ let singletonClient = "generic";
461
+
462
+ /** Lazy process-level diagnostic recorder singleton; instantiated only on reportable failures or explicit CLI queries. */
463
+ export function getIncidentRecorder(client = singletonClient): IncidentRecorder {
464
+ if (!singletonRecorder || (client !== "generic" && client !== singletonClient)) {
465
+ singletonClient = client;
466
+ singletonRecorder = new IncidentRecorder({ runtime: { client, packageVersion: PLUGIN_VERSION } });
467
+ }
468
+ return singletonRecorder;
469
+ }
470
+
471
+ export function resetIncidentRecorderForTests(): void {
472
+ singletonRecorder = null;
473
+ singletonClient = "generic";
474
+ }
@@ -1,8 +1,27 @@
1
+ import type { FaultMetadata } from "../faults";
2
+
1
3
  export type EditErrorCode =
2
4
  | "INVALID_INPUT" | "NOT_FOUND" | "AMBIGUOUS_MATCH" | "OVERLAPPING_EDITS" | "HASH_MISMATCH"
3
5
  | "UNSUPPORTED_FILE" | "UNENCODABLE" | "AMBIGUOUS_ENCODING" | "STALE_READ" | "STALE_PLAN"
4
6
  | "CANCELLED" | "TEMP_WRITE_FAILED" | "VERIFY_FAILED" | "COMMIT_UNKNOWN";
5
7
 
8
+ const EDIT_ERROR_MAP: Readonly<Record<EditErrorCode, Omit<FaultMetadata, "outcome" | "applied" | "verified" | "committed">>> = {
9
+ INVALID_INPUT: { code: "INVALID_INPUT", category: "input", phase: "validate", retryable: false, actionHint: "Fix the edit input parameters and retry." },
10
+ 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." },
11
+ AMBIGUOUS_MATCH: { code: "CONFLICT", category: "conflict", phase: "validate", retryable: true, actionHint: "Provide more context or use hashlines anchors for an exact match." },
12
+ OVERLAPPING_EDITS: { code: "INVALID_INPUT", category: "input", phase: "validate", retryable: false, actionHint: "Make edit ranges disjoint and retry." },
13
+ HASH_MISMATCH: { code: "STALE_VERSION", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read the file with hashlines=true and use the updated anchors." },
14
+ 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." },
15
+ UNENCODABLE: { code: "UNMAPPABLE", category: "policy", phase: "encode", retryable: false, actionHint: "Replace unmappable characters or convert the file encoding explicitly via charset_fix." },
16
+ 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." },
17
+ 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." },
18
+ 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." },
19
+ CANCELLED: { code: "CANCELLED", category: "io", phase: "commit", retryable: true, actionHint: "Retry if the cancellation was unintentional." },
20
+ TEMP_WRITE_FAILED: { code: "WRITE_FAILED", category: "io", phase: "commit", retryable: true, actionHint: "Check directory permissions and free disk space, then retry." },
21
+ 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." },
22
+ COMMIT_UNKNOWN: { code: "WRITE_FAILED", category: "io", phase: "commit", retryable: false, actionHint: "Re-read the file to confirm on-disk state before retrying." },
23
+ };
24
+
6
25
  export class EditError extends Error {
7
26
  readonly code: EditErrorCode;
8
27
  readonly commitState: "not_applied" | "unknown";
@@ -12,6 +31,18 @@ export class EditError extends Error {
12
31
  this.commitState = commitState;
13
32
  this.name = "EditError";
14
33
  }
34
+
35
+ toFaultMetadata(): FaultMetadata {
36
+ const base = EDIT_ERROR_MAP[this.code];
37
+ const outcome = this.commitState === "not_applied" ? "not_applied" : "uncertain";
38
+ return {
39
+ ...base,
40
+ outcome,
41
+ applied: false,
42
+ verified: false,
43
+ committed: false,
44
+ };
45
+ }
15
46
  }
16
47
 
17
48
  export function lineAt(text: string, offset: number): number {
package/src/faults.ts ADDED
@@ -0,0 +1,165 @@
1
+ // Canonical typed fault contract shared across core I/O, edit/patch engines, grep, CLI, and MCP.
2
+ // Error classification always originates from typed codes at the source — never parsed from human-readable text.
3
+
4
+ export type FaultCode =
5
+ // Expected operational / policy rejections (never recorded as internal bugs)
6
+ | "INVALID_INPUT"
7
+ | "UNMAPPABLE"
8
+ | "UNKNOWN_ENCODING"
9
+ | "AMBIGUOUS_ENCODING"
10
+ | "MIXED_EOL"
11
+ | "STALE_VERSION"
12
+ | "STALE_READ"
13
+ | "CONFLICT"
14
+ | "CANCELLED"
15
+ | "PERMISSION_DENIED"
16
+ | "NOT_FOUND"
17
+ | "BINARY_FILE"
18
+ | "UNSUPPORTED_FILE"
19
+ | "LOCK_BUSY"
20
+ | "WRITE_FAILED"
21
+ // Reportable internal / invariant / compatibility faults
22
+ | "WRITE_VERIFY_FAILED"
23
+ | "ROLLBACK_FAILED"
24
+ | "BYTE_INVARIANT_FAILED"
25
+ | "MCP_PROTOCOL_ERROR"
26
+ | "CLIENT_STARTUP_FAILED"
27
+ | "TOOL_BYPASS_DETECTED"
28
+ | "LOCK_INVARIANT_FAILED"
29
+ | "GIT_INDEX_INVARIANT_FAILED"
30
+ | "SEARCH_ENGINE_FAILED"
31
+ | "INTERNAL";
32
+
33
+ export type FaultCategory =
34
+ | "input"
35
+ | "policy"
36
+ | "conflict"
37
+ | "io"
38
+ | "engine"
39
+ | "compatibility"
40
+ | "critical";
41
+
42
+ export type FaultPhase =
43
+ | "startup"
44
+ | "detect"
45
+ | "decode"
46
+ | "validate"
47
+ | "encode"
48
+ | "commit"
49
+ | "verify"
50
+ | "rollback"
51
+ | "transport"
52
+ | "search"
53
+ | "policy"
54
+ | "unknown";
55
+
56
+ export type FaultOutcome =
57
+ | "not_applied"
58
+ | "rolled_back"
59
+ | "applied_verified"
60
+ | "uncertain"
61
+ | "unknown";
62
+
63
+ export interface FaultMetadata {
64
+ readonly code: FaultCode;
65
+ readonly category: FaultCategory;
66
+ readonly phase: FaultPhase;
67
+ readonly outcome: FaultOutcome;
68
+ readonly retryable: boolean;
69
+ readonly actionHint: string;
70
+ readonly applied?: boolean;
71
+ readonly verified?: boolean;
72
+ readonly committed?: boolean;
73
+ readonly encoding?: string;
74
+ readonly eol?: string;
75
+ readonly fileBytes?: number;
76
+ }
77
+
78
+ export const REPORTABLE_FAULT_CODES: ReadonlySet<FaultCode> = new Set([
79
+ "WRITE_VERIFY_FAILED",
80
+ "ROLLBACK_FAILED",
81
+ "BYTE_INVARIANT_FAILED",
82
+ "MCP_PROTOCOL_ERROR",
83
+ "CLIENT_STARTUP_FAILED",
84
+ "TOOL_BYPASS_DETECTED",
85
+ "LOCK_INVARIANT_FAILED",
86
+ "GIT_INDEX_INVARIANT_FAILED",
87
+ "SEARCH_ENGINE_FAILED",
88
+ "INTERNAL",
89
+ ]);
90
+
91
+ export interface McpErrorEnvelope {
92
+ readonly status: "failed";
93
+ readonly error: {
94
+ readonly code: FaultCode;
95
+ readonly category: FaultCategory;
96
+ readonly phase: FaultPhase;
97
+ readonly retryable: boolean;
98
+ };
99
+ readonly applied: boolean;
100
+ readonly verified: boolean;
101
+ readonly committed: boolean;
102
+ readonly outcome: FaultOutcome;
103
+ readonly actionHint: string;
104
+ }
105
+
106
+ export class CharsetFault extends Error {
107
+ readonly fault: FaultMetadata;
108
+
109
+ constructor(message: string, fault: FaultMetadata) {
110
+ super(message);
111
+ this.name = "CharsetFault";
112
+ this.fault = Object.freeze({ ...fault });
113
+ }
114
+
115
+ get code(): FaultCode {
116
+ return this.fault.code;
117
+ }
118
+
119
+ get outcome(): FaultOutcome {
120
+ return this.fault.outcome;
121
+ }
122
+
123
+ get reportable(): boolean {
124
+ return REPORTABLE_FAULT_CODES.has(this.fault.code);
125
+ }
126
+
127
+ toMcpEnvelope(): McpErrorEnvelope {
128
+ const f = this.fault;
129
+ return {
130
+ status: "failed",
131
+ error: {
132
+ code: f.code,
133
+ category: f.category,
134
+ phase: f.phase,
135
+ retryable: f.retryable,
136
+ },
137
+ applied: f.applied ?? false,
138
+ verified: f.verified ?? false,
139
+ committed: f.committed ?? false,
140
+ outcome: f.outcome,
141
+ actionHint: f.actionHint,
142
+ };
143
+ }
144
+ }
145
+
146
+ export function isCharsetFault(err: unknown): err is CharsetFault {
147
+ return err instanceof CharsetFault;
148
+ }
149
+
150
+ export function toMcpErrorEnvelope(fault: FaultMetadata): McpErrorEnvelope {
151
+ return {
152
+ status: "failed",
153
+ error: {
154
+ code: fault.code,
155
+ category: fault.category,
156
+ phase: fault.phase,
157
+ retryable: fault.retryable,
158
+ },
159
+ applied: fault.applied ?? false,
160
+ verified: fault.verified ?? false,
161
+ committed: fault.committed ?? false,
162
+ outcome: fault.outcome,
163
+ actionHint: fault.actionHint,
164
+ };
165
+ }