pi-charset 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,33 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.1.9] - 2026-12-06
13
+
14
+ ### Added
15
+
16
+ - **Standard MCP Tool Annotations (`src/mcp/server.ts`)**: Declared MCP `annotations` (`title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint: false`) across all 7 tools (`charset_read`, `charset_grep`, `charset_check` marked read-only & non-destructive; all tools marked strictly local `openWorldHint: false`).
17
+ - **Codex `default_tools_approval_mode` Auto-Config & `doctor --fix` Upgrade (`src/setup/adapters.ts`, `tools/pi-charset-cli.mjs`)**: `pi-charset setup` and `mcp-config` now emit `default_tools_approval_mode = "approve"` under `[mcp_servers.pi-charset]` (preserving explicit user-configured values and exact rollback), and `pi-charset doctor` detects older Codex entries missing `default_tools_approval_mode` as `degraded` so `doctor --fix` upgrades them seamlessly for `workspace-write` / `codex exec`.
18
+ - **9-Encoding Adversarial & Protocol Hardening Matrix (`test/adversarial-matrix.test.ts`)**: Added end-to-end stdio MCP verification covering 9 encodings (including 4-byte GB18030 `𠮷`/`𠀀`/`€`, Big5, Shift_JIS, EUC-KR, UTF-16LE/BE BOM, UTF-8 BOM/plain), atomic 5-encoding multi-file `apply_patch` + batch undo, zero-orphan-directory rejected writes, `Content-Type`-first multi-header framing, concurrent read/write linearization, and short-GBK ambiguity regression.
19
+
20
+ ### Fixed
21
+
22
+ - **Short-GBK Cross-Family Scoring & Single-Family Ambiguity (`src/encoding/classify.ts`)**: Eliminated EUC-KR Hangul+Hanja double-counting above 100% total weight by scaling the Hanzi term by `(1 - hangulRatio)` when Hangul is present and raising the 8+ syllable common-Hangul threshold to `0.35`, and narrowed `crossFamilyAmbiguous` strictly to encoding families that actually pass lossless round-trip (eliminating false ambiguity rejections on short GBK files while preserving GBK-with-kana, Big5, Shift_JIS, and EUC-KR accuracy).
23
+ - **Zero-Config UTF-8-Native Format Guard (`src/config.ts`)**: Prevented zero-config sibling inference from inheriting legacy CJK encodings from unrelated `.c`/`.h`/`.txt` siblings onto new or pure-ASCII UTF-8-mandated formats (`.json`, `.toml`, `.yaml`, `.yml`, `.ts`, `.tsx`, `.mjs`, `.rs`, `.go`, `.md`, `.svg`), while preserving existing legacy files and explicit `.pi-charset.json` rules.
24
+ - **Readers-Writer Concurrent MCP Dispatch & Multi-Header Framing (`src/mcp/server.ts`)**: Replaced global FIFO serialization with a Readers-Writer barrier allowing up to 8 concurrent read-only calls (`charset_read`, `charset_grep`, `charset_check`) with linearizable write-after-read / read-after-write ordering, atomic stdout frame serialization, LSP/MCP `Content-Type`-before-`Content-Length` header support, 32 MiB frame bounds checking, and corrected the `charset_read` missing-path fault operation tag (`"read"`).
25
+ - **Zero-Orphan-Directory Non-Destructive Write (`src/operations.ts`, `src/mcp/server.ts`)**: Deferred `mkdir(dirname, { recursive: true })` until after `expectedVersion`, Gate 3, Gate 1, NUL checks, and `STALE_READ` all pass.
26
+ - **Lazy DBCS Encodability Bitset & Fast ASCII-Run DFA Scan (`src/encoding/fast-codec.ts`)**: Deferred the 65,536-iteration `bmpEncodable` table build until first write/edit check (eliminating unnecessary warm-up work on read/classify/grep paths) and hoisted an inner ASCII-run loop in `fastExactRoundTrip`.
27
+ - **Windows `.cmd`/`.ps1` CLI Discovery (`src/setup/adapters.ts`)**: Replaced slow `spawnSync("--version")` probing in `probeBinary` with direct `PATH`/`PATHEXT` resolution (including `.cmd`/`.bat`/`.ps1` on Windows), fixing `cliPath: null` false negatives for `pi`, `codex`, and `claude` on Windows and speeding up `pi-charset doctor`.
28
+
29
+ ## [0.1.8] - 2026-12-06
30
+
31
+ ### Added
32
+
33
+ - **Unified Typed Fault Contract (`src/faults.ts`)**: Replaced ad-hoc string errors across core I/O (`src/operations.ts`), edit/patch diagnostics (`src/edit/diagnostics.ts`), and MCP (`src/mcp/server.ts`) with typed `CharsetFault` / `FaultMetadata` (`code`, `category`, `phase`, `outcome`, `retryable`, `actionHint`) and a consistent machine-readable MCP error envelope (`status: "failed"`, `error`, `applied`, `verified`, `committed`, `outcome`, `actionHint`) on every failure branch.
34
+ - **Privacy-First Local Incident Recorder (`src/diagnostics/incidents.ts`) & `pi-charset feedback`**: Integrated a zero-network, bounded, allowlist-only local diagnostic recorder (never records source code, paths, raw exception strings, prompts, or secrets; ignores expected operational rejections; deduplicates across independent OS processes with daily slot caps, 14-day retention pruning, fingerprint tamper verification, and safe fallback on filesystems without hard-link support; disable via `PI_CHARSET_DIAGNOSTICS=0`). Added `pi-charset feedback list | preview <fp> | issue-url <fp> | prune | clear`.
35
+ - **Host Adapter Registry & One-Command `pi-charset setup` (`src/setup/adapters.ts`)**: Added idempotent, atomic, non-destructive setup, `--dry-run`, `--uninstall`, and `--rollback` for Codex (`~/.codex/config.toml`), Antigravity (`~/.gemini/config/mcp_config.json`), Claude Code, and Cursor using permanent absolute `node` + `pi-charset-mcp.mjs` entrypoints (preserving all third-party MCP servers and refusing to overwrite invalid JSON), paired with an isolated temp-dir synthetic GBK+CRLF `read`/`edit`/`undo` smoke test.
36
+ - **Upgraded `pi-charset doctor --json` / `--fix` & Selective AGY `_meta`**: `doctor --json` now reports Node compatibility, live MCP smoke verification, honest per-client status (`not_installed` / `unregistered` / `registered` / `handshake_verified` / `degraded`), Git hook enforcement, and local diagnostics state; `doctor --fix` repairs only broken `pi-charset`-owned MCP entries. Added selective `_meta: { "antigravity/alwaysLoad": true }` to the 3 high-frequency core MCP tools (`charset_read`, `charset_edit`, `charset_grep`).
37
+ - **Cross-Process & Windows Path Hardening Tests**: Added independent multi-OS-process `pi-charset-mcp` concurrency tests (`expectedVersion` across separate processes), complex Chinese/space/parenthesis/bracket path tests, full privacy/dedup/retention tests, and isolated `HOME` adapter setup/rollback tests (`test/diagnostics-incidents.test.ts`, `test/setup-adapters.test.ts`, `test/cross-process-and-faults.test.ts`).
38
+
12
39
  ## [0.1.7] - 2026-12-06
13
40
 
14
41
  ### Fixed
@@ -8,6 +8,33 @@
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.1.9] - 2026-12-06
12
+
13
+ ### 新增
14
+
15
+ - **标准 MCP 工具注解(`src/mcp/server.ts`)**:为全部 7 个 MCP 工具补齐标准 `annotations`(`title`、`readOnlyHint`、`destructiveHint`、`idempotentHint`、`openWorldHint: false`),其中 `charset_read`、`charset_grep`、`charset_check` 标记为只读无破坏性,全部工具标记为纯本地零联网。
16
+ - **Codex `default_tools_approval_mode` 自动配置与 `doctor --fix` 升级(`src/setup/adapters.ts`、`tools/pi-charset-cli.mjs`)**:`pi-charset setup` 与 `mcp-config` 写入 `[mcp_servers.pi-charset]` 时默认带上 `default_tools_approval_mode = "approve"`(保留用户手动自定义值与精确回滚),`pi-charset doctor` 会识别缺失该项的旧 Codex 注册为 `degraded` 并支持 `doctor --fix` 一键升级,解决 `workspace-write` / `codex exec` 下的 MCP 审批拦截问题。
17
+ - **9 编码对抗与协议加固回归矩阵(`test/adversarial-matrix.test.ts`)**:新增覆盖 9 种编码(含 GB18030 四字节 `𠮷`/`𠀀`/`€`、Big5、Shift_JIS、EUC-KR、UTF-16LE/BE BOM、UTF-8 BOM/纯文本)读写改 + dry-run/实操逐字节撤销、单次原子补丁跨 5 种编码 + 批量回滚、拒写零残留空目录、`Content-Type` 前置帧、并发读写屏障以及短 GBK 单家族无歧义回归测试。
18
+
19
+ ### 修复
20
+
21
+ - **短 GBK 跨家族打分双重计分与单家族误报歧义(`src/encoding/classify.ts`)**:当存在韩文时按 `1 - hangulRatio` 对汉字项做凸组合缩放并将长串韩文常用音节门槛提高到 `0.35`,杜绝 EUC-KR 乱码同时叠加汉字+韩文超过 100% 权重;并在全量往返后仅在真正无损通过的家族集合内判定跨家族歧义,彻底消除短 GBK 文件误报歧义拒写(同时完整保留 GBK+日文假名、Big5、Shift_JIS 与 EUC-KR 识别准确率)。
22
+ - **零配置现代 UTF-8 原生格式防误污染保护(`src/config.ts`)**:在零配置混编仓库中,新建或纯 ASCII 的 UTF-8 原生格式(`.json`、`.toml`、`.yaml`、`.yml`、`.ts`、`.tsx`、`.mjs`、`.rs`、`.go`、`.md`、`.svg`)不再从无关的 `.c`/`.h`/`.txt` 兄弟文件误继承旧 CJK 编码(磁盘已有旧编码与显式 `.pi-charset.json` 规则不受影响)。
23
+ - **MCP 读写锁屏障并发调度与多头部帧加固(`src/mcp/server.ts`)**:将全局串行链升级为读写锁屏障(支持最多 8 路并发只读调用与线性一致的写后读/读后写、原子 stdout 帧输出不交错),支持 `Content-Type` 位于 `Content-Length` 之前的标准多头部帧、32 MiB 帧上限防护,并修正 `charset_read` 缺参错误日志误标 `"edit"` 为 `"read"`。
24
+ - **拒写零残留空目录(`src/operations.ts`、`src/mcp/server.ts`)**:将 `mkdir(..., { recursive: true })` 延迟至 `expectedVersion`、Gate 3、Gate 1、NUL 检查与 `STALE_READ` 全部通过之后执行,保证被拒绝的新路径写入零文件系统副作用。
25
+ - **DBCS 编码位图惰性编译与 ASCII 连续扫描优化(`src/encoding/fast-codec.ts`)**:将 65,536 项 `bmpEncodable` 位图改为首次写入校验时惰性构建(消除读/分类/搜索路径上的多余预热),并在 `fastExactRoundTrip` 中提取连续 ASCII 快速跳过内循环。
26
+ - **Windows `.cmd`/`.ps1` CLI 探测修复(`src/setup/adapters.ts`)**:将 `probeBinary` 从慢速 `spawnSync("--version")` 改为直接扫描 `PATH`/`PATHEXT`(含 `.cmd`/`.bat`/`.ps1`),修复 Windows 下 `doctor` 将 `pi`/`codex`/`claude` 误报为 `cliPath: null` 并显著缩短 `doctor` 耗时。
27
+
28
+ ## [0.1.8] - 2026-12-06
29
+
30
+ ### 新增
31
+
32
+ - **统一类型化故障契约(`src/faults.ts`)**:在核心 I/O(`src/operations.ts`)、编辑诊断(`src/edit/diagnostics.ts`)与 MCP 服务(`src/mcp/server.ts`)全链路落地 `CharsetFault` / `FaultMetadata`(`code`、`category`、`phase`、`outcome`、`retryable`、`actionHint`),确保所有失败分支均返回稳定结构化错误信封(`status: "failed"`、`error`、`applied`、`verified`、`committed`、`outcome`、`actionHint`),彻底消除从人类文本反推错误码。
33
+ - **隐私优先本地诊断记录器(`src/diagnostics/incidents.ts`)与 `pi-charset feedback`**:集成零联网、有界内存与磁盘配额的纯白名单本地故障记录器(严禁记录源码、路径、原始异常文本、提示词或凭据;自动忽略正常安全拒绝;支持独立 OS 进程跨进程去重、每日槽位上限、14 天留存清理、篡改指纹校验及无 hardlink 文件系统安全回退;设 `PI_CHARSET_DIAGNOSTICS=0` 可彻底关闭),并在 CLI 新增 `pi-charset feedback list | preview <指纹> | issue-url <指纹> | prune | clear`。
34
+ - **Host Adapter Registry 与真正的一键 `pi-charset setup`(`src/setup/adapters.ts`)**:为 Codex(`~/.codex/config.toml`)、Antigravity(`~/.gemini/config/mcp_config.json`)、Claude Code 与 Cursor 提供幂等、原子、无损的 `setup` / `--dry-run` / `--uninstall` / `--rollback`,写入永久绝对路径的 `node` + `pi-charset-mcp.mjs` 入口(完整保留第三方 MCP 配置,遇非法 JSON 拒绝覆盖),并在隔离临时目录执行合成 GBK+CRLF `read`/`edit`/`undo` 端到端自检。
35
+ - **升级 `pi-charset doctor --json` / `--fix` 与 AGY 选择性 `_meta`**:`doctor --json` 输出稳定的机器可读诊断状态(严格区分 `not_installed` / `unregistered` / `registered` / `handshake_verified` / `degraded` 与真实防护边界);`doctor --fix` 仅安全修复 `pi-charset` 自有失效条目,绝不触碰用户源码或自定义钩子;在 3 个高频核心 MCP 工具(`charset_read`、`charset_edit`、`charset_grep`)上选择性标记 `_meta: { "antigravity/alwaysLoad": true }`。
36
+ - **独立多进程并发与全套硬化回归测试**:新增双独立 OS 进程 `pi-charset-mcp` 并发 `expectedVersion` 验证、中文/空格/括号/方括号复杂路径测试、隐私与跨进程去重测试以及隔离 `HOME` 安装/回滚/卸载测试(`test/diagnostics-incidents.test.ts`、`test/setup-adapters.test.ts`、`test/cross-process-and-faults.test.ts`)。
37
+
11
38
  ## [0.1.7] - 2026-12-06
12
39
 
13
40
  ### 修复
package/dist/config.js CHANGED
@@ -407,7 +407,19 @@ function nextParentDir(cur) {
407
407
  * Scan up to 16 sibling text files in `dir` (falling back up to 3 parent dirs for newly created/empty subdirectories)
408
408
  * to infer the dominant encoding and line-ending style when creating a new file or adding non-ASCII text to a pure-ASCII file.
409
409
  */
410
+ // Formats whose specifications or modern toolchains mandate UTF-8: in zero-config mode, new or pure-ASCII files
411
+ // with these extensions never inherit legacy CJK encodings from unrelated sibling files (e.g. `.c`/`.h`/`.txt`).
412
+ // Existing files that already contain non-ASCII legacy bytes on disk are still classified by their own bytes.
413
+ const UTF8_NATIVE_EXT = new Set([
414
+ ".json", ".jsonc", ".json5", ".jsonl",
415
+ ".toml", ".yaml", ".yml",
416
+ ".ts", ".tsx", ".mts", ".cts", ".mjs",
417
+ ".rs", ".go",
418
+ ".md", ".mdx", ".svg",
419
+ ]);
410
420
  function inferFromSiblings(dir, targetExt, excludeBase) {
421
+ if (UTF8_NATIVE_EXT.has(targetExt))
422
+ return { encoding: "UTF-8", eol: null };
411
423
  let cur = path.resolve(dir);
412
424
  for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
413
425
  if (depth > 0 && isBoundaryDir(cur))
@@ -451,6 +463,8 @@ function inferFromSiblings(dir, targetExt, excludeBase) {
451
463
  }
452
464
  /** Non-blocking sibling inference (with parent & project-file fallback for empty/new subdirectories) used on async hot paths. */
453
465
  async function inferFromSiblingsAsync(dir, targetExt, excludeBase) {
466
+ if (UTF8_NATIVE_EXT.has(targetExt))
467
+ return { encoding: "UTF-8", eol: null };
454
468
  let cur = path.resolve(dir);
455
469
  for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
456
470
  if (depth > 0 && isBoundaryDir(cur))
@@ -0,0 +1,436 @@
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.js";
9
+ const SCHEMA = 1;
10
+ const CODES = Object.freeze({
11
+ WRITE_VERIFY_FAILED: ["engine", "Verify rollback and reproduce using a synthetic encoded fixture."],
12
+ ROLLBACK_FAILED: ["critical", "Stop further writes; inspect local recovery journal."],
13
+ BYTE_INVARIANT_FAILED: ["critical", "Stop further writes; compare synthetic byte-preservation fixture."],
14
+ MCP_PROTOCOL_ERROR: ["compatibility", "Reproduce initialize, tools/list and tools/call with a synthetic client."],
15
+ CLIENT_STARTUP_FAILED: ["compatibility", "Check installed package entrypoint, runtime and stdio handshake."],
16
+ TOOL_BYPASS_DETECTED: ["compatibility", "Check client rules and hooks; inspect local Git diff."],
17
+ LOCK_INVARIANT_FAILED: ["engine", "Reproduce with separate processes and concurrent writes."],
18
+ GIT_INDEX_INVARIANT_FAILED: ["critical", "Reproduce in a temporary repository with staged changes."],
19
+ SEARCH_ENGINE_FAILED: ["compatibility", "Reproduce with synthetic legacy-encoded files and ripgrep."],
20
+ INTERNAL: ["engine", "Reproduce the failed operation with a minimal synthetic fixture."],
21
+ });
22
+ const EXPECTED_REJECTIONS = new Set([
23
+ "INVALID_INPUT",
24
+ "UNMAPPABLE",
25
+ "UNKNOWN_ENCODING",
26
+ "AMBIGUOUS_ENCODING",
27
+ "MIXED_EOL",
28
+ "STALE_VERSION",
29
+ "STALE_READ",
30
+ "CONFLICT",
31
+ "CANCELLED",
32
+ "PERMISSION_DENIED",
33
+ "NOT_FOUND",
34
+ "BINARY_FILE",
35
+ "UNSUPPORTED_FILE",
36
+ "LOCK_BUSY",
37
+ ]);
38
+ const OPS = [
39
+ "read", "write", "edit", "apply_patch", "grep", "check", "fix", "undo",
40
+ "setup", "initialize", "tools_list", "hook", "unknown",
41
+ ];
42
+ const CLIENTS = [
43
+ "pi", "codex", "agy", "antigravity-ide", "antigravity-app",
44
+ "claude", "cursor", "windsurf", "generic", "unknown",
45
+ ];
46
+ const ENCODINGS = [
47
+ "ASCII", "UTF-8", "UTF-16LE", "UTF-16BE", "GBK", "GB18030",
48
+ "BIG5", "SHIFT_JIS", "EUC-KR", "EUC-JP", "ISO-8859-1", "UNKNOWN", "unknown",
49
+ ];
50
+ const PHASES = [
51
+ "startup", "detect", "decode", "validate", "encode", "commit",
52
+ "verify", "rollback", "transport", "search", "policy", "unknown",
53
+ ];
54
+ const OUTCOMES = ["not_applied", "rolled_back", "applied_verified", "uncertain", "unknown"];
55
+ const PLATFORMS = ["win32", "linux", "darwin", "unknown"];
56
+ const ARCHS = ["x64", "arm64", "ia32", "unknown"];
57
+ const EOLS = ["LF", "CRLF", "CR", "MIXED", "NONE", "unknown"];
58
+ const SIZE_BUCKETS = ["lt4KiB", "4-64KiB", "64KiB-1MiB", "1-10MiB", "gte10MiB", "unknown"];
59
+ function enumValue(v, allowed) {
60
+ return typeof v === "string" && allowed.includes(v) ? v : "unknown";
61
+ }
62
+ function sanitizeVersion(v) {
63
+ return typeof v === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[0-9A-Za-z.-]{1,24})?$/.test(v) ? v : "unknown";
64
+ }
65
+ function dayString(date) {
66
+ return date.toISOString().slice(0, 10);
67
+ }
68
+ function bucketSize(v) {
69
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0)
70
+ return "unknown";
71
+ if (v < 4096)
72
+ return "lt4KiB";
73
+ if (v < 65536)
74
+ return "4-64KiB";
75
+ if (v < 1048576)
76
+ return "64KiB-1MiB";
77
+ if (v < 10485760)
78
+ return "1-10MiB";
79
+ return "gte10MiB";
80
+ }
81
+ function fingerprintFields(fields) {
82
+ return createHash("sha256").update(JSON.stringify(fields)).digest("hex").slice(0, 32);
83
+ }
84
+ export function normalizeIncident(input = {}, runtime = {}) {
85
+ if (!input || typeof input !== "object")
86
+ return null;
87
+ const code = input.code;
88
+ if (typeof code !== "string" || EXPECTED_REJECTIONS.has(code) || !Object.hasOwn(CODES, code))
89
+ return null;
90
+ const typedCode = code;
91
+ const fields = {
92
+ schema: SCHEMA,
93
+ code: typedCode,
94
+ category: CODES[typedCode][0],
95
+ operation: enumValue(input.operation, OPS),
96
+ phase: enumValue(input.phase, PHASES),
97
+ outcome: enumValue(input.outcome, OUTCOMES),
98
+ client: enumValue(runtime.client, CLIENTS),
99
+ packageVersion: sanitizeVersion(runtime.packageVersion ?? PLUGIN_VERSION),
100
+ platform: enumValue(runtime.platform ?? process.platform, PLATFORMS),
101
+ arch: enumValue(runtime.arch ?? process.arch, ARCHS),
102
+ nodeMajor: Math.min(99, Math.max(0, Number(process.versions.node.split(".")[0]) || 0)),
103
+ encoding: enumValue(typeof input.encoding === "string" ? input.encoding.toUpperCase() : "unknown", ENCODINGS),
104
+ eol: enumValue(input.eol, EOLS),
105
+ sizeBucket: bucketSize(input.fileBytes),
106
+ };
107
+ return Object.freeze({ ...fields, fingerprint: fingerprintFields(fields) });
108
+ }
109
+ export function diagnosticsStateRoot() {
110
+ if (process.env.PI_CHARSET_DIAGNOSTICS_DIR?.trim()) {
111
+ return path.resolve(process.env.PI_CHARSET_DIAGNOSTICS_DIR.trim());
112
+ }
113
+ if (process.platform === "win32") {
114
+ return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"), "pi-charset", "diagnostics-v1");
115
+ }
116
+ if (process.platform === "darwin") {
117
+ return path.join(os.homedir(), "Library", "Application Support", "pi-charset", "diagnostics-v1");
118
+ }
119
+ return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"), "pi-charset", "diagnostics-v1");
120
+ }
121
+ /** Respect user-level opt-out (env var only; never overridden by project .pi-charset.json or model prompts). */
122
+ export function isDiagnosticsEnabledByEnv() {
123
+ const v = (process.env.PI_CHARSET_DIAGNOSTICS ?? "").trim().toLowerCase();
124
+ if (v === "0" || v === "false" || v === "off" || v === "no")
125
+ return false;
126
+ return true;
127
+ }
128
+ const isDayDir = (v) => /^\d{4}-\d{2}-\d{2}$/.test(v);
129
+ const isSlotFile = (v) => /^slot-\d{3}\.json$/.test(v);
130
+ const isTempFile = (v) => /^\.tmp-[0-9a-f]{24}$/.test(v);
131
+ async function safeDir(dir) {
132
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
133
+ const s = await fs.lstat(dir);
134
+ if (!s.isDirectory() || s.isSymbolicLink())
135
+ throw new Error("unsafe diagnostic directory");
136
+ }
137
+ function validatePersisted(v) {
138
+ if (!v || typeof v !== "object")
139
+ return null;
140
+ const obj = v;
141
+ if (obj.schema !== SCHEMA || typeof obj.code !== "string" || !Object.hasOwn(CODES, obj.code))
142
+ return null;
143
+ const typedCode = obj.code;
144
+ const fields = {
145
+ schema: SCHEMA,
146
+ code: typedCode,
147
+ category: CODES[typedCode][0],
148
+ operation: enumValue(obj.operation, OPS),
149
+ phase: enumValue(obj.phase, PHASES),
150
+ outcome: enumValue(obj.outcome, OUTCOMES),
151
+ client: enumValue(obj.client, CLIENTS),
152
+ packageVersion: sanitizeVersion(obj.packageVersion),
153
+ platform: enumValue(obj.platform, PLATFORMS),
154
+ arch: enumValue(obj.arch, ARCHS),
155
+ nodeMajor: typeof obj.nodeMajor === "number" && Number.isInteger(obj.nodeMajor) && obj.nodeMajor >= 0 && obj.nodeMajor <= 99 ? obj.nodeMajor : 0,
156
+ encoding: enumValue(obj.encoding, ENCODINGS),
157
+ eol: enumValue(obj.eol, EOLS),
158
+ sizeBucket: enumValue(obj.sizeBucket, SIZE_BUCKETS),
159
+ };
160
+ const fingerprint = fingerprintFields(fields);
161
+ if (obj.fingerprint !== fingerprint)
162
+ return null;
163
+ return { ...fields, fingerprint };
164
+ }
165
+ async function readRecord(file) {
166
+ try {
167
+ const st = await fs.lstat(file);
168
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 4096)
169
+ return null;
170
+ return validatePersisted(JSON.parse(await fs.readFile(file, "utf8")));
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ export function issueDraft(report) {
177
+ const r = validatePersisted(report);
178
+ if (!r)
179
+ throw new Error("Invalid incident report");
180
+ return {
181
+ title: `[${r.code}] ${r.operation} / ${r.client} / ${r.platform}`,
182
+ body: `## Sanitized diagnostic\n\n` +
183
+ `Fingerprint: \`${r.fingerprint}\`\n\n` +
184
+ `\`\`\`json\n${JSON.stringify(r, null, 2)}\n\`\`\`\n\n` +
185
+ `## Suggested reproduction\n\n` +
186
+ `${CODES[r.code][1]}\n\n` +
187
+ `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`,
188
+ };
189
+ }
190
+ export function buildIssueUrl(report, repo = "ethan-blue/pi-charset") {
191
+ const draft = issueDraft(report);
192
+ const url = new URL(`https://github.com/${repo}/issues/new`);
193
+ url.searchParams.set("title", draft.title);
194
+ url.searchParams.set("body", draft.body);
195
+ return url.href;
196
+ }
197
+ export class IncidentRecorder {
198
+ root;
199
+ enabled;
200
+ runtime;
201
+ slots;
202
+ retention;
203
+ maxPending;
204
+ clock;
205
+ #pending = [];
206
+ #drain = null;
207
+ #seen = new Set();
208
+ #lastPrune = "";
209
+ constructor(opts = {}) {
210
+ this.root = path.resolve(opts.root ?? diagnosticsStateRoot());
211
+ this.enabled = opts.enabled !== undefined ? opts.enabled === true : isDiagnosticsEnabledByEnv();
212
+ this.runtime = { packageVersion: PLUGIN_VERSION, ...opts.runtime };
213
+ this.slots = Math.max(1, Math.min(256, Math.floor(opts.slotsPerDay ?? 64) || 64));
214
+ this.retention = Math.max(1, Math.min(30, Math.floor(opts.retentionDays ?? 14) || 14));
215
+ this.maxPending = Math.max(1, Math.min(128, Math.floor(opts.maxPending ?? 32) || 32));
216
+ this.clock = opts.clock ?? (() => new Date());
217
+ }
218
+ /** Fire-and-forget on reportable failure only; bounded memory, zero stdout logging, never throws. */
219
+ record(input) {
220
+ try {
221
+ if (!this.enabled)
222
+ return { status: "disabled" };
223
+ const event = normalizeIncident(input, this.runtime);
224
+ if (!event)
225
+ return { status: "ignored" };
226
+ const date = dayString(this.clock());
227
+ const key = `${date}:${event.fingerprint}`;
228
+ if (this.#seen.has(key))
229
+ return { status: "duplicate", fingerprint: event.fingerprint };
230
+ if (this.#pending.length >= this.maxPending)
231
+ return { status: "queue_full" };
232
+ this.#seen.add(key);
233
+ if (this.#seen.size > 512) {
234
+ this.#seen.clear();
235
+ this.#seen.add(key);
236
+ }
237
+ this.#pending.push({ date, event, key });
238
+ this.#startDrain();
239
+ return { status: "queued", fingerprint: event.fingerprint };
240
+ }
241
+ catch {
242
+ return { status: "unavailable" };
243
+ }
244
+ }
245
+ #startDrain() {
246
+ if (this.#drain)
247
+ return;
248
+ this.#drain = this.#run().finally(() => {
249
+ this.#drain = null;
250
+ if (this.#pending.length)
251
+ this.#startDrain();
252
+ });
253
+ }
254
+ async #publishSlot(temp, dest, payload) {
255
+ try {
256
+ await fs.link(temp, dest);
257
+ return "published";
258
+ }
259
+ catch (error) {
260
+ const code = error?.code;
261
+ if (code === "EEXIST")
262
+ return "exists";
263
+ // Safe fallback for filesystems without hard-link support (e.g. FAT32/exFAT/network mounts).
264
+ if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV" || code === "EACCES" || code === "ENOSYS") {
265
+ try {
266
+ await fs.writeFile(dest, payload, { flag: "wx", mode: 0o600 });
267
+ return "published";
268
+ }
269
+ catch (wxErr) {
270
+ if (wxErr?.code === "EEXIST")
271
+ return "exists";
272
+ throw wxErr;
273
+ }
274
+ }
275
+ throw error;
276
+ }
277
+ }
278
+ async #run() {
279
+ while (this.#pending.length) {
280
+ const item = this.#pending.shift();
281
+ const { date, event, key } = item;
282
+ try {
283
+ await safeDir(this.root);
284
+ if (this.#lastPrune !== date) {
285
+ await this.prune();
286
+ this.#lastPrune = date;
287
+ }
288
+ const dir = path.join(this.root, date);
289
+ await safeDir(dir);
290
+ const payload = JSON.stringify(event) + "\n";
291
+ const temp = path.join(dir, `.tmp-${randomBytes(12).toString("hex")}`);
292
+ try {
293
+ await fs.writeFile(temp, payload, { flag: "wx", mode: 0o600 });
294
+ const start = parseInt(event.fingerprint.slice(0, 8), 16) % this.slots;
295
+ for (let i = 0; i < this.slots; i++) {
296
+ const dest = path.join(dir, `slot-${String((start + i) % this.slots).padStart(3, "0")}.json`);
297
+ const pub = await this.#publishSlot(temp, dest, payload);
298
+ if (pub === "published")
299
+ break;
300
+ const existing = await readRecord(dest);
301
+ if (existing?.fingerprint === event.fingerprint)
302
+ break;
303
+ }
304
+ }
305
+ finally {
306
+ await fs.unlink(temp).catch(() => undefined);
307
+ }
308
+ }
309
+ catch {
310
+ this.#seen.delete(key);
311
+ // Diagnostic I/O must never alter or block tool results.
312
+ }
313
+ }
314
+ }
315
+ async flush(timeoutMs = 1500) {
316
+ const waitAll = async () => {
317
+ while (this.#drain)
318
+ await this.#drain;
319
+ };
320
+ if (timeoutMs <= 0) {
321
+ await waitAll();
322
+ return;
323
+ }
324
+ await Promise.race([
325
+ waitAll(),
326
+ new Promise((resolve) => {
327
+ const t = setTimeout(resolve, timeoutMs);
328
+ t.unref?.();
329
+ }),
330
+ ]);
331
+ }
332
+ async prune() {
333
+ const cutoff = new Date(this.clock().getTime() - (this.retention - 1) * 86400000).toISOString().slice(0, 10);
334
+ let dirs;
335
+ try {
336
+ dirs = await fs.readdir(this.root, { withFileTypes: true });
337
+ }
338
+ catch {
339
+ return;
340
+ }
341
+ for (const d of dirs) {
342
+ if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name))
343
+ continue;
344
+ const expired = d.name < cutoff;
345
+ const dir = path.join(this.root, d.name);
346
+ try {
347
+ for (const f of await fs.readdir(dir, { withFileTypes: true })) {
348
+ if (!f.isFile() || f.isSymbolicLink() || !(isSlotFile(f.name) || isTempFile(f.name)))
349
+ continue;
350
+ const full = path.join(dir, f.name);
351
+ if ((expired && isSlotFile(f.name)) ||
352
+ (isTempFile(f.name) && this.clock().getTime() - (await fs.stat(full)).mtimeMs > 86400000)) {
353
+ await fs.unlink(full).catch(() => undefined);
354
+ }
355
+ }
356
+ if (expired)
357
+ await fs.rmdir(dir).catch(() => undefined);
358
+ }
359
+ catch { /* Concurrent process may prune first. */ }
360
+ }
361
+ }
362
+ async clear() {
363
+ await this.flush();
364
+ this.#seen.clear();
365
+ let removed = 0;
366
+ let dirs;
367
+ try {
368
+ dirs = await fs.readdir(this.root, { withFileTypes: true });
369
+ }
370
+ catch {
371
+ return 0;
372
+ }
373
+ for (const d of dirs) {
374
+ if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name))
375
+ continue;
376
+ const dir = path.join(this.root, d.name);
377
+ try {
378
+ for (const f of await fs.readdir(dir, { withFileTypes: true })) {
379
+ if (!f.isFile() || f.isSymbolicLink() || !(isSlotFile(f.name) || isTempFile(f.name)))
380
+ continue;
381
+ await fs.unlink(path.join(dir, f.name)).catch(() => undefined);
382
+ if (isSlotFile(f.name))
383
+ removed++;
384
+ }
385
+ await fs.rmdir(dir).catch(() => undefined);
386
+ }
387
+ catch { /* ignore */ }
388
+ }
389
+ return removed;
390
+ }
391
+ async list() {
392
+ await this.flush();
393
+ const out = [];
394
+ let dirs;
395
+ try {
396
+ dirs = await fs.readdir(this.root, { withFileTypes: true });
397
+ }
398
+ catch {
399
+ return out;
400
+ }
401
+ for (const d of dirs) {
402
+ if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name))
403
+ continue;
404
+ const dir = path.join(this.root, d.name);
405
+ let files;
406
+ try {
407
+ files = await fs.readdir(dir, { withFileTypes: true });
408
+ }
409
+ catch {
410
+ continue;
411
+ }
412
+ for (const f of files) {
413
+ if (!f.isFile() || !isSlotFile(f.name))
414
+ continue;
415
+ const report = await readRecord(path.join(dir, f.name));
416
+ if (report)
417
+ out.push({ date: d.name, report });
418
+ }
419
+ }
420
+ return out.sort((a, b) => b.date.localeCompare(a.date) || a.report.fingerprint.localeCompare(b.report.fingerprint));
421
+ }
422
+ }
423
+ let singletonRecorder = null;
424
+ let singletonClient = "generic";
425
+ /** Lazy process-level diagnostic recorder singleton; instantiated only on reportable failures or explicit CLI queries. */
426
+ export function getIncidentRecorder(client = singletonClient) {
427
+ if (!singletonRecorder || (client !== "generic" && client !== singletonClient)) {
428
+ singletonClient = client;
429
+ singletonRecorder = new IncidentRecorder({ runtime: { client, packageVersion: PLUGIN_VERSION } });
430
+ }
431
+ return singletonRecorder;
432
+ }
433
+ export function resetIncidentRecorderForTests() {
434
+ singletonRecorder = null;
435
+ singletonClient = "generic";
436
+ }
@@ -1,3 +1,19 @@
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
+ };
1
17
  export class EditError extends Error {
2
18
  code;
3
19
  commitState;
@@ -7,6 +23,17 @@ export class EditError extends Error {
7
23
  this.commitState = commitState;
8
24
  this.name = "EditError";
9
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
+ }
10
37
  }
11
38
  export function lineAt(text, offset) {
12
39
  let count = 1;
@@ -104,7 +104,10 @@ export function decideFamilyFromBuffers(samples, families, perBufferLimit = SCRI
104
104
  // bonuses only count when the decoded script itself looks real: kana capped below a strong hanzi score,
105
105
  // Hangul gated by its own frequency skew.
106
106
  // Frequency carries twice the weight of commonness: GBK text read as Big5 still looks "common".
107
- let score = common / Math.max(1, han) + (2 * top) / Math.max(1, han) - (2 * fffd) / nonAscii;
107
+ // When Hangul is present, scale the Hanzi term by (1 - hangulRatio) so EUC-KR mojibake (mostly garbage
108
+ // Hangul plus 2-3 stray Hanja) cannot double-count 100% Hanzi + Hangul bonus above 100% total weight.
109
+ const hanWeight = hangul > 0 ? 1 - hangulRatio : 1;
110
+ let score = hanWeight * (common / Math.max(1, han) + (2 * top) / Math.max(1, han)) - (2 * fffd) / nonAscii;
108
111
  // Script bonuses need enough evidence: a handful of noise syllables can hit the common set by chance.
109
112
  if ((family === "Shift_JIS" || family === "EUC-JP") && kana >= 4) {
110
113
  // Kana rows are shared with GB2312, so the kanji decide: real Japanese kanji are common words.
@@ -112,7 +115,7 @@ export function decideFamilyFromBuffers(samples, families, perBufferLimit = SCRI
112
115
  }
113
116
  if (family === "EUC-KR" && hangul >= 3) {
114
117
  const pure = commonHangul / hangul;
115
- score += hangulRatio * ((hangul >= 8 && pure >= 0.2) || pure >= 0.5 ? 1.5 : 0.2);
118
+ score += hangulRatio * ((hangul >= 8 && pure >= 0.35) || pure >= 0.5 ? 1.5 : 0.2);
116
119
  }
117
120
  scores.push([family, score]);
118
121
  }
@@ -357,13 +360,31 @@ function classifyUncached(B, cfg, opts) {
357
360
  return { ...configVerdict(B, pref, "undecidable"), kind: "config" };
358
361
  return { kind: "unknown", encoding: "UNKNOWN", ambiguous: false, hasFffd: true, candidates: [], exhaustive: true, bom: false };
359
362
  }
360
- const chosen = pref && pass.includes(pref) ? pref : pass[0];
363
+ let finalPass = pass;
364
+ if (exhaustive && crossFamilyAmbiguous) {
365
+ const passFamilies = new Set(pass.map(familyOf));
366
+ if (passFamilies.size <= 1) {
367
+ // Only a single encoding family round-tripped losslessly; impossible families cannot create cross-family ambiguity.
368
+ crossFamilyAmbiguous = false;
369
+ family = [...passFamilies][0] ?? family;
370
+ }
371
+ else {
372
+ // Re-score strictly among families that actually passed lossless round-trip so failing families cannot spoil the margin.
373
+ const narrowed = decideFamily(B, passFamilies);
374
+ if (narrowed.confident && narrowed.family) {
375
+ crossFamilyAmbiguous = false;
376
+ family = narrowed.family;
377
+ finalPass = preferFamily(pass, narrowed.family);
378
+ }
379
+ }
380
+ }
381
+ const chosen = pref && finalPass.includes(pref) ? pref : finalPass[0];
361
382
  return {
362
383
  kind: "cjk",
363
384
  encoding: chosen,
364
- ambiguous: exhaustive ? pass.length > 1 : pass.length > 1 || order.length > pass.length,
385
+ ambiguous: exhaustive ? finalPass.length > 1 : finalPass.length > 1 || order.length > finalPass.length,
365
386
  hasFffd: false,
366
- candidates: pass,
387
+ candidates: finalPass,
367
388
  exhaustive,
368
389
  bom: false,
369
390
  family,