pi-charset 0.1.8 → 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,23 @@ 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
+
12
29
  ## [0.1.8] - 2026-12-06
13
30
 
14
31
  ### Added
@@ -8,6 +8,23 @@
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
+
11
28
  ## [0.1.8] - 2026-12-06
12
29
 
13
30
  ### 新增
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))
@@ -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,
@@ -185,13 +185,13 @@ function compileDbcs(encoding) {
185
185
  break;
186
186
  }
187
187
  }
188
- const bmpEncodable = new Uint8Array(8192);
189
188
  let asciiIdentity = true;
190
- for (let cp = 0; cp < 0x10000; cp++) {
191
- if (cp >= 0xd800 && cp <= 0xdfff)
192
- continue;
193
- const bucket = encodeTable[cp >> 8];
194
- const mb = bucket !== undefined ? bucket[cp & 0xff] : UNASSIGNED;
189
+ let asciiEncodable = true;
190
+ const asciiBucket = encodeTable[0];
191
+ for (let cp = 0; cp < 128; cp++) {
192
+ const mb = asciiBucket !== undefined ? asciiBucket[cp] : UNASSIGNED;
193
+ if (mb !== cp)
194
+ asciiIdentity = false;
195
195
  let ok = false;
196
196
  if (mb >= 0 && (gb18030 || mb < 0x1000000)) {
197
197
  ok = decodeMbCode(decodeTables, mb) === cp;
@@ -199,24 +199,16 @@ function compileDbcs(encoding) {
199
199
  else if (mb === UNASSIGNED && gb18030) {
200
200
  ok = gb18030CodePointEncodable(cp, gb18030, encodeTable);
201
201
  }
202
- if (ok)
203
- bmpEncodable[cp >> 3] |= 1 << (cp & 7);
204
- if (cp < 128 && mb !== cp)
205
- asciiIdentity = false;
206
- }
207
- let asciiEncodable = true;
208
- for (let cp = 0; cp < 128; cp++) {
209
- if ((bmpEncodable[cp >> 3] & (1 << (cp & 7))) === 0) {
202
+ if (!ok)
210
203
  asciiEncodable = false;
211
- break;
212
- }
213
204
  }
214
205
  const compiled = {
215
206
  dfa,
216
207
  asciiFast,
217
208
  gb18030,
209
+ decodeTables,
218
210
  encodeTable,
219
- bmpEncodable,
211
+ bmpEncodable: null,
220
212
  hasEncodeSeq,
221
213
  asciiEncodable,
222
214
  bmpToMb: null,
@@ -226,6 +218,29 @@ function compileDbcs(encoding) {
226
218
  compiledCache.set(encoding, compiled);
227
219
  return compiled;
228
220
  }
221
+ function getBmpEncodable(c) {
222
+ if (c.bmpEncodable)
223
+ return c.bmpEncodable;
224
+ const bits = new Uint8Array(8192);
225
+ const { encodeTable, decodeTables, gb18030 } = c;
226
+ for (let cp = 0; cp < 0x10000; cp++) {
227
+ if (cp >= 0xd800 && cp <= 0xdfff)
228
+ continue;
229
+ const bucket = encodeTable[cp >> 8];
230
+ const mb = bucket !== undefined ? bucket[cp & 0xff] : UNASSIGNED;
231
+ let ok = false;
232
+ if (mb >= 0 && (gb18030 || mb < 0x1000000)) {
233
+ ok = decodeMbCode(decodeTables, mb) === cp;
234
+ }
235
+ else if (mb === UNASSIGNED && gb18030) {
236
+ ok = gb18030CodePointEncodable(cp, gb18030, encodeTable);
237
+ }
238
+ if (ok)
239
+ bits[cp >> 3] |= 1 << (cp & 7);
240
+ }
241
+ c.bmpEncodable = bits;
242
+ return bits;
243
+ }
229
244
  function getBmpEncodeTable(c) {
230
245
  if (c.bmpToMb)
231
246
  return c.bmpToMb;
@@ -256,35 +271,71 @@ export function fastExactRoundTrip(buf, encoding) {
256
271
  const root = dfa[0];
257
272
  let node = root;
258
273
  const len = buf.length;
259
- const asciiFast = c.asciiFast;
260
274
  let icuSafe = c.icuDecoder !== null;
261
- for (let i = 0; i < len; i++) {
262
- const b = buf[i];
263
- if (asciiFast && node === root && b < 0x80)
264
- continue;
265
- const v = node[b];
266
- if (v === DFA_VALID) {
267
- node = root;
268
- }
269
- else if (v < 0) {
270
- node = dfa[-v];
271
- }
272
- else if (v === DFA_VALID_ICU_DIFF) {
273
- icuSafe = false;
274
- node = root;
275
- }
276
- else if (v === DFA_GB18030 && c.gb18030 && i >= 3) {
277
- icuSafe = false;
278
- const ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (b - 0x30);
279
- if (!gb18030PtrValid(ptr, c.gb18030, c.encodeTable))
275
+ if (c.asciiFast) {
276
+ let i = 0;
277
+ while (i < len) {
278
+ if (node === root) {
279
+ while (i < len && buf[i] < 0x80)
280
+ i++;
281
+ if (i >= len)
282
+ break;
283
+ }
284
+ const b = buf[i];
285
+ const v = node[b];
286
+ if (v === DFA_VALID) {
287
+ node = root;
288
+ }
289
+ else if (v < 0) {
290
+ node = dfa[-v];
291
+ }
292
+ else if (v === DFA_VALID_ICU_DIFF) {
293
+ icuSafe = false;
294
+ node = root;
295
+ }
296
+ else if (v === DFA_GB18030 && c.gb18030 && i >= 3) {
297
+ icuSafe = false;
298
+ const ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (b - 0x30);
299
+ if (!gb18030PtrValid(ptr, c.gb18030, c.encodeTable))
300
+ return false;
301
+ node = root;
302
+ }
303
+ else if (v === DFA_FALLBACK) {
304
+ return null;
305
+ }
306
+ else {
280
307
  return false;
281
- node = root;
282
- }
283
- else if (v === DFA_FALLBACK) {
284
- return null;
308
+ }
309
+ i++;
285
310
  }
286
- else {
287
- return false;
311
+ }
312
+ else {
313
+ for (let i = 0; i < len; i++) {
314
+ const b = buf[i];
315
+ const v = node[b];
316
+ if (v === DFA_VALID) {
317
+ node = root;
318
+ }
319
+ else if (v < 0) {
320
+ node = dfa[-v];
321
+ }
322
+ else if (v === DFA_VALID_ICU_DIFF) {
323
+ icuSafe = false;
324
+ node = root;
325
+ }
326
+ else if (v === DFA_GB18030 && c.gb18030 && i >= 3) {
327
+ icuSafe = false;
328
+ const ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (b - 0x30);
329
+ if (!gb18030PtrValid(ptr, c.gb18030, c.encodeTable))
330
+ return false;
331
+ node = root;
332
+ }
333
+ else if (v === DFA_FALLBACK) {
334
+ return null;
335
+ }
336
+ else {
337
+ return false;
338
+ }
288
339
  }
289
340
  }
290
341
  if (node !== root)
@@ -431,7 +482,7 @@ export function fastCanEncodeAll(text, encoding) {
431
482
  return null;
432
483
  if (c.asciiEncodable && !NON_ASCII_STR.test(text))
433
484
  return true;
434
- const bits = c.bmpEncodable;
485
+ const bits = getBmpEncodable(c);
435
486
  const asciiOk = c.asciiEncodable;
436
487
  const len = text.length;
437
488
  for (let i = 0; i < len; i++) {