pi-charset 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/CHANGELOG.zh-CN.md +64 -0
  3. package/CONTRIBUTING.md +33 -0
  4. package/CONTRIBUTING.zh-CN.md +33 -0
  5. package/README.md +35 -6
  6. package/README.zh-CN.md +35 -6
  7. package/docs/ACCEPTANCE.md +30 -2
  8. package/docs/COMPATIBILITY.md +6 -1
  9. package/docs/CONFIG-GUIDE.md +4 -1
  10. package/docs/DESIGN-REVIEW.md +54 -0
  11. package/docs/EDIT-ENGINE.md +46 -0
  12. package/docs/EDITING-PLAN.md +16 -0
  13. package/docs/MCP-AND-MULTI-AGENT.md +111 -0
  14. package/docs/MODEL-EVAL.md +92 -0
  15. package/docs/PROGRESS.md +311 -0
  16. package/docs/RELEASING.md +4 -2
  17. package/docs/zh-CN/ACCEPTANCE.md +30 -2
  18. package/docs/zh-CN/COMPATIBILITY.md +6 -1
  19. package/docs/zh-CN/CONFIG-GUIDE.md +4 -1
  20. package/docs/zh-CN/DESIGN-REVIEW.md +54 -0
  21. package/docs/zh-CN/EDIT-ENGINE.md +46 -0
  22. package/docs/zh-CN/EDITING-PLAN.md +415 -0
  23. package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +111 -0
  24. package/docs/zh-CN/MODEL-EVAL.md +92 -0
  25. package/docs/zh-CN/PROGRESS.md +311 -0
  26. package/docs/zh-CN/RELEASING.md +4 -2
  27. package/docs/zh-CN/editing-plan-architecture.png +0 -0
  28. package/examples/all-utf8.jsonc +1 -0
  29. package/examples/embedded-c.jsonc +1 -0
  30. package/examples/legacy-java-web.jsonc +1 -0
  31. package/examples/mixed-repo.jsonc +1 -0
  32. package/package.json +14 -2
  33. package/prompts/charset-setup.md +3 -3
  34. package/schema/pi-charset.schema.json +118 -0
  35. package/skills/charset-rules/SKILL.md +8 -2
  36. package/src/config.ts +524 -185
  37. package/src/edit/apply-patch-core.ts +275 -0
  38. package/src/edit/apply-patch.ts +78 -0
  39. package/src/edit/diagnostics.ts +48 -0
  40. package/src/edit/hashline.ts +438 -0
  41. package/src/edit/patch.ts +655 -0
  42. package/src/edit/paths.ts +42 -0
  43. package/src/edit/plan.ts +107 -0
  44. package/src/edit/tool.ts +451 -0
  45. package/src/edit-preview.ts +48 -277
  46. package/src/encoding/classify.ts +235 -65
  47. package/src/encoding/common-scripts.ts +66 -0
  48. package/src/encoding/converter.ts +114 -16
  49. package/src/encoding/fast-codec.ts +469 -0
  50. package/src/encoding/file-stamp.ts +55 -0
  51. package/src/encoding/line-endings.ts +66 -73
  52. package/src/encoding/mime.ts +12 -43
  53. package/src/encoding/stream-transcode.ts +135 -30
  54. package/src/grep-core.ts +687 -0
  55. package/src/grep.ts +25 -463
  56. package/src/index.ts +458 -49
  57. package/src/journal.ts +459 -0
  58. package/src/maintenance.ts +375 -0
  59. package/src/mcp/server.ts +651 -0
  60. package/src/operations.ts +759 -127
  61. package/src/read-view.ts +924 -0
  62. package/src/resolve.ts +113 -101
  63. package/src/scaffold.ts +9 -4
  64. package/src/shell-guard.ts +617 -0
  65. package/src/shell.ts +85 -33
  66. package/src/sysnote.ts +4 -6
  67. package/src/version.ts +1 -1
  68. package/tools/charset-core.mjs +251 -0
  69. package/tools/pi-charset-cli.mjs +369 -0
  70. package/tools/pi-charset-mcp.mjs +103 -0
  71. package/tools/scan-encoding.mjs +30 -28
package/CHANGELOG.md CHANGED
@@ -7,6 +7,70 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
 
8
8
  ---
9
9
 
10
+ ## [Unreleased]
11
+
12
+ ## [0.1.6] - 2026-12-06
13
+
14
+ ### Added
15
+
16
+ - Add same-core zero-dependency stdio MCP server (`src/mcp/server.ts`, `tools/pi-charset-mcp.mjs`, `bin.pi-charset-mcp`) exposing `charset_read`, `charset_write`, `charset_edit`, `charset_apply_patch`, `charset_grep`, `charset_check`, and `charset_fix` so Codex, Antigravity, Claude Code, and Cursor run on the exact same Pi-independent core (`src/grep-core.ts`, `src/edit/paths.ts`, `src/edit/apply-patch-core.ts`) with **zero `.pi-charset.json` files required** (supports pure zero-config mode plus optional CLI flags `--encoding`/`--eol`/`--prefer-legacy`/`--hashlines`/`--auto-commit` and `PI_CHARSET_*` env vars, MCP `initialize.instructions`, `resources/list` & `prompts/list` probes, JSON-RPC batch arrays, `EPIPE` safe exit, and defensive LLM `file_path`/JSON-string argument coercion).
17
+ - Add opt-in `preferSourceOverUtf8` config/override option (and JSON Schema + CLI parity) to prevent tiny BOM-less GBK headers whose bytes accidentally satisfy UTF-8 grammar from being hijacked as UTF-8.
18
+ - Add `pi-charset install-hook [--strict-eol] [--force]` (worktree-safe Git `pre-commit` gate installer) and `pi-charset mcp-config [--client codex|antigravity|claude|generic]` to `tools/pi-charset-cli.mjs`, plus bilingual multi-agent guide (`docs/MCP-AND-MULTI-AGENT.md` / `docs/zh-CN/MCP-AND-MULTI-AGENT.md`).
19
+
20
+ ### Fixed
21
+
22
+ - Fix `tools/charset-core.mjs` to honor an explicitly declared multi-byte `sourceEncoding` directly when it round-trips losslessly (matching `src/encoding/classify.ts` and preventing short GBK comments from being misclassified as `EUC-KR` by `pi-charset check`).
23
+
24
+ ## [0.1.5] - 2026-12-06
25
+
26
+ ### Changed
27
+
28
+ - Slim and consolidate shared core plumbing across `src/` and `tools/` (net −125 production lines with zero API or behavior regressions): unify project-hint discovery onto one stamp-validated cached `detectProjectHints` in `src/config.ts` (**42× faster** warm lookups), share BOM/lock/workspace-scan helpers across `src/operations.ts` and `src/maintenance.ts`, unify sync/async `rg` executable discovery in `src/grep.ts`, share CLI argument tokenization across `src/scaffold.ts` and `src/index.ts`, cache per-directory config lookup in `tools/pi-charset-cli.mjs`, fix single-entry raw-size gating in `decodedReadCache` so 2.2 MiB GBK files hit warm cache (**0.04–0.06 ms**, **166×–254× faster**), and upgrade `formatHashlines` and anchor verification (`src/edit/hashline.ts`) to single-pass zero-slice `lineHashRange` scanning (**19.7 ms** for 100k lines).
29
+ - Unify `tools/scan-encoding.mjs` and `tools/pi-charset-cli.mjs` onto one shared classifier/EOL/hint module (`tools/charset-core.mjs`, eliminating duplicate classifier drift and adding UTF-16 lone-surrogate & CJK cross-family parity to the CI gate); upgrade `decodedReadCache` into a unified `read` + `edit` snapshot cache (`loadSnapshot` reuses fresh `read` buffers); stream `formatLineRanges` without full-file `LineSpan[]` allocation (O(1) memory, stops at max requested line); extend `locale: "en"` across Gate 3, `/charset-status`, and `/charset-undo`; unwrap outer Markdown fences in `edit(patch)` and `apply_patch`; add proactive `[EOL: MIXED]` hints on `read`, `$schema` links to `examples/*.jsonc`, and smart mixed-repo UTF-8 redirect pass-through in `shellGuard`.
30
+ - Count distinct, encoding-verified grep matches toward the result limit.
31
+ - Use one exact edit plan for preview and execution in all encodings. Repeated or overlapping matches are rejected; fuzzy normalization is no longer applied. A no-op does not overwrite the file.
32
+ - Bind edits to a per-session observed version and immutable snapshot, preserving encoding, BOM, line endings, and untouched bytes. Reject stale previews, unsupported links, and unencodable replacements before writing.
33
+ - Return bounded source hints and distinguish pre-replacement errors from uncertain or failed post-replacement verification.
34
+ - Decode only the lines a search prints or verifies and classify hit files without the exhaustive candidate list; the first search over a legacy-encoded tree is about 3.5× faster with byte-identical output. ASCII-only hit lines skip classification and file access entirely, which also surfaces them in text whose encoding cannot be determined.
35
+ - Compile zero-allocation DBCS round-trip DFA, BMP encodability bitsets, flat `Uint16Array` encoder, proven-clean native ICU `TextDecoder` decode, and exact raw byte-splicing for edits (`src/encoding/fast-codec.ts`); 1 MiB GBK edit drops to **18.5 ms** (10 MiB GBK 879 → **132.8 ms**, 10 MiB UTF-8 415 → **67.6 ms**); lazily build `COMMON_HAN`, window large-file edit diffs, and reuse ripgrep's verified line text without extra ConHost overhead on Windows (tying native `grep` at ~17 ms on UTF-8 trees and running 3.2× faster on GBK trees).
36
+ - Run the encoding search passes concurrently with sound encodability pass pruning (skipping non-UTF-8 passes that cannot represent caseless non-ASCII literal characters, cutting 2,000-file mixed-encoding search to **142 ms**) and stop remaining passes once one fills the limit: a regex over a 2,048-file tree 463 → 271 ms, a Chinese literal over a GBK tree 109 → 34 ms.
37
+ - Compress all 5 registered tool schemas (`read`, `write`, `edit`, `apply_patch`, `grep`) and `ENCODING_NOTE` so total per-turn prompt overhead drops **−50.3%** (6,068 → 3,016 chars; **−27.4% smaller than Native Pi's 4 tools**, and still **−21.4% smaller** even with `ENCODING_NOTE`).
38
+ - Classify legacy bytes narrowest-first with an early stop, reuse that verdict for the read and write plans, and cache sibling inference per directory: zero-config reads of legacy files are about 4× faster, and repeated reads inside a legacy directory about 50× faster.
39
+
40
+ ### Added
41
+
42
+ - Add zero-config "install & forget" upgrades: auto-search all encodable East Asian CJK families (GB18030 / Big5 / Shift_JIS / EUC-KR / EUC-JP) in zero-config `grep` with zero extra passes for Simplified Chinese via encodability pruning; auto-inherit declared encoding/EOL from `.editorconfig`, `.gitattributes`, `pom.xml`, and `CMakeLists.txt` in zero-config mode; add write-through hot caching after verified >=64 KiB `edit` commits for instant chained edits; expand Gate 1 typographic replacement hints (40+ symbols) and majority-EOL recommendations; add one-command `/charset` health check & `/charset fix` batch auto-repair (with atomic `/charset-undo`) plus a once-per-session `U+FFFD` shell mojibake auto-hint.
43
+ - Add nanosecond-stamped 16 MiB decoded-read cache (`src/operations.ts`, `src/encoding/file-stamp.ts`, **300×+ faster** cached 2 MiB GBK reads at **0.036 ms**), pure-ASCII C++ fast paths in `fastEncodeDbcs`/`fastCanEncodeAll` (**14× faster**), zero-alloc no-op `restoreLineEndings` (**7× faster**), and C++ UTF-16LE/BE EOL detection (`src/encoding/line-endings.ts`), plus reproducible perf/eval harness `test/perf/eval-benchmark.test.ts`.
44
+ - Add controlled maintenance & observability commands (`src/maintenance.ts`): `/charset-explain <path>` (full decision trace + `.editorconfig`/`.gitattributes`/`pom.xml`/`CMakeLists.txt` project hints), `/charset-normalize-eol <path> --to crlf|lf [--dry-run]`, and `/charset-convert <path> --to <encoding> [--bom|--no-bom] [--dry-run]` (Gate 1/2 verified + `/charset-undo` journaled), non-UTF-8 `details.charset` metadata & TUI badge on `read`, unified machine-readable error codes (`[GATE1_UNMAPPABLE; not_applied]`, `[MIXED_EOL; not_applied]`, `[STALE_READ; not_applied]`, etc.), `locale` (`"auto" | "en" | "zh-CN"`), and Gate 1 `@L<line>:<col>` + safe ASCII replacement suggestions for common LLM typography characters.
45
+ - Add exact `[..endLine]` block ranges and `offset`/`limit` pagination to `read(outline=true)`, aggregated multi-file pre-flight diagnostics to `apply_patch`, zero-config parent-directory sibling fallback (up to 3 levels) for newly created subdirectories, `force: true` single-byte encoding search in `grep` (e.g. `windows-1252`), IDE JSON Schema (`schema/pi-charset.schema.json`), and team CI/pre-commit gate CLI (`tools/pi-charset-cli.mjs` / `npx pi-charset check --staged --strict-eol`).
46
+ - Add `shellGuard` (`"block"` | `"warn"` | `"off"`, default `"block"` when `.pi-charset.json` applies or when targeting non-UTF-8 files/directories in zero-config mode) via Pi's `tool_call` hook: blocks encoding-bypassing shell commands (`python -c` file writes / `chardet`, `iconv`/`dos2unix`, `sed -i`/`perl -pi`/`awk -i inplace`, `node -e` `writeFile*`, PowerShell `Set-Content`/`Out-File`/`[IO.File]::WriteAll*`, and source-file heredoc/echo redirects) before execution while allowing builds, tests, git, and read-only scripts.
47
+ - Four encoding-safe editing modes on `edit` (`edits` Search/Replace, `hashlines` content-addressed line anchors with post-edit updated-anchor feedback, OMP anchor dialects, echoed-prefix absorption, shift-aware `HASH_MISMATCH` recovery, and `NOOP_LOOP` guard, `patch` supporting unified diff / Codex hunks / Aider `SEARCH/REPLACE` blocks, and `wholeFile`), plus multi-file `apply_patch` (Codex `*** Begin Patch` including `*** Hashline File:`, Aider multi-file `SEARCH/REPLACE`, and `diff --git`) with all-or-nothing pre-flight validation, deadlock-free sorted path locking, and `/charset-undo` support for added and deleted files.
48
+ - Token-efficient views on `read` (`outline: true` structural symbol outlines with `<line>:<2-hex>|` anchors supporting multi-line signatures, nested constructs, C++ class constructors, C/C++/TS/JS/Python/Java/Go/Rust/SQL/Proto/Lua/Ruby/Elixir/CMake/CSS/Markdown/config, and immunity to block comments, multi-line JS templates, Go/Rust/C++ raw strings, Java text blocks, Python docstrings, and Markdown fences; plus `ranges: [[start, end], ...]` single-pass multi-slice reads, cutting large-file navigation/inspection tokens by **17×–42×**) and `grep` (`filesOnly: true` file+count discovery and `hashlines: true` direct-to-edit anchors).
49
+ - `/charset-undo`: session-scoped undo (32 MiB bounded) with atomic batch undo for multi-file `apply_patch` (all-or-nothing `lstat` + writability + hash pre-flight verification across updates, adds, deletes, and moves under sorted path locks), supporting `list`, `b<batch>` / `batch:<batch>`, `#<id>`, and `<path>` (without shadowing filenames like `b1` or `12`), plus out-of-order and external-edit refusal guards.
50
+ - `autoCommit` option: after a verified write, commit only that file to git with a path-limited commit.
51
+
52
+ ### Fixed
53
+
54
+ - Achieve 100% native Pi tool parity across `read`, `write`, `edit`, `apply_patch`, `grep`, and `bash`/`powershell`: keep `read` `structuredContent` synchronized after `hashlines`/`outline`/`ranges`/notes, skip hash-tagging on `firstLineExceedsLimit` errors, support `file_path` alias and macOS NFD/curly-apostrophe/AM-PM path resolution in `read`/`write`, coerce JSON-stringified/single-object `hashlines` and `ranges` (including alongside explicit `undefined` keys), scope `NOOP_LOOP` detection to session epoch, emit empty-line anchors on empty-string Hashline replacements, colorize expanded `edit` diffs via `renderDiff`, honor `ctx.cwd` and `~`/`@path` expansion in `grep`, expose `constrainedSampling` and `renderShell: "self"` on `apply_patch` (plus Gate 2 verification and updated-hashline feedback on `Move`), forward `shellPath` and `commandPrefix` when `transcodeBash` is enabled, and upgrade `shellGuard` to a quote- and heredoc-aware command segmenter eliminating false positives on `git commit`/`rg`/`echo` arguments while catching nested `bash -c`/`pwsh -Command`/`node -p`/quoted-semicolon evasions.
55
+ - Fix `stream-transcode.ts` locking into passthrough after >64 KiB of pure-ASCII output (so late GBK compiler errors still transcode) and mis-decoding UTF-16LE/BE BOM shell output as GB18030; fix PowerShell `Get-Content` flag-value parsing and per-cwd dynamic shell rules in `src/shell.ts`; upgrade `tools/scan-encoding.mjs` to match v0.1.5 BOM/UTF-32/UTF-16 validation and CJK cross-family disambiguation so `/charset-init` never mis-scaffolds Shift_JIS/Big5/EUC-KR repos as GBK.
56
+ - Unify cache evidence across `classify`, `config`, `siblingInference`, and `grep` (`src/encoding/file-stamp.ts`: `dev`/`ino`/`size`/`mtimeMs`/`ctimeMs`), bump `configGeneration()` on external `.pi-charset.json` changes, share one `invalidatePathCaches` path across `write`/`edit`/`apply_patch`/`undo`, move sibling inference, ripgrep discovery, config lookup in `read`/`/charset-status`, and Windows `chcp` detection onto non-blocking async hot paths, reuse cold-miss `raw` bytes across multi-file `grep` (bounded at 16 MiB, one disk read per cold file instead of two), and deduplicate `HASH_MISMATCH` surrounding context lines and edit input validators.
57
+ - Fix `/charset-undo <path>` selecting the oldest instead of newest journal entry when a file was edited multiple times, fix `/charset-undo #<id>` resolving via path instead of exact ID, bound session journal heap retention to 32 MiB (storing `afterSha1`/`afterBytes` and evicting expired batches atomically), serialize git `autoCommit` per repo with atomic batch commits for `apply_patch`, reject `*** Move to:` in single-file `edit(patch)`, report already-committed files and revert batch ID on partial `apply_patch` failures, and add TUI `renderCall`/`renderResult` rendering to `apply_patch`.
58
+ - Align line-1 Hashline hashes and `outline` detection across `read(outline)`, `read(hashlines)`, `read(ranges)`, `grep(hashlines)`, and `edit(hashlines)` on UTF-8 BOM files while preserving the BOM on disk.
59
+ - Keep UTF-16 BOM matches from ripgrep's automatic pass and preserve line numbering with bare CR.
60
+ - Reject edits that would turn a text file into a binary file under the byte classifier.
61
+ - Keep escaped source hints within the diagnostic byte budget.
62
+ - Check relative links against the packaged files and include both contribution guides.
63
+ - Keep prereleases on the npm `next` channel and mark them as prereleases on GitHub.
64
+ - Reject `write` to a hard-linked file instead of silently breaking the link, matching `edit`.
65
+ - Refuse `write` over bytes that no encoding can decode in zero-config mode. The second classification under the rule's UTF-8 preference used to relabel them as decodable and overwrite them as UTF-8.
66
+ - Enforce RFC 3629 validity in `incompleteUtf8Tail`, handle mid-character `sampleBytes` cuts in streaming shell transcoding, slice each sibling from its first non-ASCII byte without cross-file byte concatenation, and clean up the `stop` AbortSignal listener in `runRgPass`.
67
+ - Report the UNKNOWN notice when reading undecidable bytes in zero-config mode, not only under a configuration.
68
+ - Tell CJK families apart by the decoded text. Big5, Shift_JIS, EUC-JP and EUC-KR files used to be read as GBK (and new text written as GBK into them) because they also round-trip as GBK; bytes with no script evidence are now marked `crossFamilyAmbiguous` and refuse non-ASCII writes with `AMBIGUOUS_ENCODING` until an encoding is declared.
69
+
70
+ ### Removed
71
+
72
+ - Unused helpers: `verdictForBuffer`, `planBomBytes`, `detectLineEnding`, `detectLineEndingFromText`, `buildEncodingGroups` and `globDirPrefix`.
73
+
10
74
  ## [0.1.4] - 2026-10-28
11
75
 
12
76
  ### Fixed
@@ -6,6 +6,70 @@
6
6
 
7
7
  ---
8
8
 
9
+ ## [Unreleased]
10
+
11
+ ## [0.1.6] - 2026-12-06
12
+
13
+ ### 新增
14
+
15
+ - 新增同源零依赖 Stdio MCP 服务(`src/mcp/server.ts`、`tools/pi-charset-mcp.mjs`、`bin.pi-charset-mcp`),对外暴露 `charset_read`、`charset_write`、`charset_edit`、`charset_apply_patch`、`charset_grep`、`charset_check` 与 `charset_fix`,让 Codex、Antigravity、Claude Code 与 Cursor **无需安装 Pi 也无需仓库内放 `.pi-charset.json`** 即可直连同一套确定性内核(支持纯零配置自适应及可选命令行参数 `--encoding`/`--eol`/`--prefer-legacy`/`--hashlines`/`--auto-commit` 与 `PI_CHARSET_*` 环境变量,并补齐 MCP `initialize.instructions`、`resources/list`/`prompts/list` 探测、JSON-RPC 批处理、`EPIPE` 优雅退出与 `file_path`/JSON 字符串参数容错)。
16
+ - 新增可选配置项 `preferSourceOverUtf8`(支持根配置、目录 override、JSON Schema 与 CLI 门禁),防止仅含寥寥几个汉字的无 BOM 极短 GBK 头文件因字节偶发符合 UTF-8 语法而被误判锁定为 UTF-8。
17
+ - 在 `tools/pi-charset-cli.mjs` 新增 `pi-charset install-hook [--strict-eol] [--force]`(兼容 `git worktree` 的 `pre-commit` 编码质检钩子一键安装)与 `pi-charset mcp-config [--client codex|antigravity|claude|generic]`,并新增中英文多工具协同文档(`docs/MCP-AND-MULTI-AGENT.md` / `docs/zh-CN/MCP-AND-MULTI-AGENT.md`)。
18
+
19
+ ### 修复
20
+
21
+ - 修复 `tools/charset-core.mjs` 在显式指定多字节 `sourceEncoding` 且无损回环时仍走跨家族启发式导致极短 GBK 注释被 `pi-charset check` 误判为 `EUC-KR` 的问题(与 `src/encoding/classify.ts` 保持完全一致)。
22
+
23
+ ## [0.1.5] - 2026-12-06
24
+
25
+ ### 变更
26
+
27
+ - 对 `src/` 与 `tools/` 实施架构收敛与代码瘦身(净减 125 行生产代码,零接口或行为回退):将项目线索探测统一至 `src/config.ts` 中带 `FileStamp` 校验缓存的 `detectProjectHints`(热命中提速 **42×**);在 `src/operations.ts` 与 `src/maintenance.ts` 之间复用 BOM、路径锁与工作区扫描内核;精简 `src/grep.ts` 同步/异步 `rg` 探测与 `src/index.ts`/`src/scaffold.ts` 命令参数解析;为 `tools/pi-charset-cli.mjs` 增加目录级配置缓存;修复 `decodedReadCache` 单条阈值按原文件字节判断,使 2.2 MiB GBK 文件稳定命中热缓存(**0.04–0.06 ms**,较朴素读解码快 **166×–254×**);将 `formatHashlines` 与锚点校验(`src/edit/hashline.ts`)升级为单趟零切片 `lineHashRange` 扫描(10 万行 **19.7 ms**)。
28
+ - 将 `tools/scan-encoding.mjs` 与 `tools/pi-charset-cli.mjs` 收敛到共享内核 `tools/charset-core.mjs`(消除三套分类器漂移并使 CI 门禁具备完整的 UTF-16 孤立代理项与 CJK 跨家族消歧);将解码读缓存升级为 `read` + `edit` 统一文件快照缓存(`loadSnapshot` 直接复用新鲜读缓冲);将 `formatLineRanges` 升级为零 `LineSpan[]` 分配的流式早停切片;完善 `locale: "en"` 对闸门 3、`/charset-status` 与 `/charset-undo` 的全链路覆盖;为 `edit(patch)` / `apply_patch` 补齐外层 Markdown 代码围栏剥离、为 `read` 补充混合换行主动提示、为全部 `examples/*.jsonc` 预设补齐 `$schema`,并使 `shellGuard` 在混合仓库中对纯 UTF-8 区域的普通重定向零打扰放行。
29
+ - grep 仅将通过编码校验并去重的命中计入结果上限。
30
+ - 所有编码共用同一精确编辑计划完成预览与执行。重复命中或相交范围会被拒绝,不再静默模糊归一化。原样替换不覆盖文件。
31
+ - 编辑绑定会话内的已读版本及文件快照,保护编码、BOM、行尾及未编辑字节。过期预览、不支持的链接或不可编码内容均在写前拦截。
32
+ - 失败时给出有限的真实原文提示,并区分写前拒绝与写后状态不明或回读失败。
33
+ - 搜索只解码需要输出或复核的行,命中文件分类不再穷尽候选列表;对传统编码工程的首次搜索约快 3.5 倍,输出逐字节不变。纯 ASCII 的命中行完全跳过分类与文件访问,编码无法判定的文本中的这类命中也会显示出来。
34
+ - 直接从 `iconv-lite` 映射表编译零分配 DBCS 往返 DFA、BMP 可编码位图、扁平 `Uint16Array` 编码器、已证明无差异的原生 C++ ICU `TextDecoder` 解码与编辑原始字节拼接(`src/encoding/fast-codec.ts`),1 MiB GBK 编辑降至 **18.5 ms**(10 MiB GBK 879 → **132.8 ms**,10 MiB UTF-8 415 → **67.6 ms**);惰性批量构建 `COMMON_HAN`,大文件编辑按改动窗口生成 diff,并在 `grep` 中直接复用 ripgrep 已验证行文本且移除 Windows ConHost 额外启动开销(UTF-8 树约 17 ms 追平原生,GBK 树比原生快 3.2 倍)。
35
+ - 多编码搜索趟并行执行,并引入基于字符集可编码性的数学剪枝(对含目标编码无法表示的定长非 ASCII 字符跳过无效 `rg` 趟,2000 文件混合编码搜索降至 **142 ms**),某一趟凑满上限即停止其余趟:2048 文件目录树上的正则 463 → 271 ms,GBK 树上的中文字面量 109 → 34 ms。
36
+ - 精简全部 5 个工具 Schema(`read`、`write`、`edit`、`apply_patch`、`grep`)与 `ENCODING_NOTE`,每轮工具定义开销下降 **50.3%**(6,068 → 3,016 字符,**比 Pi 原生 4 工具还少 27.4%**,叠加 `ENCODING_NOTE` 仍少 **21.4%**)。
37
+ - 传统编码字节按最窄优先、首个通过即停分类,读写计划复用该判定,兄弟文件推断按目录缓存:零配置下读取传统编码文件约快 4 倍,在传统编码目录内重复读取约快 50 倍。
38
+
39
+ ### 新增
40
+
41
+ - 零配置「安装即忘」傻瓜化体验全面升级:零配置 `grep` 自动覆盖全部可编码东亚 CJK 家族(GB18030 / Big5 / Shift_JIS / EUC-KR / EUC-JP,简体字经数学剪枝保持零额外趟开销);零配置自动继承工程现有的 `.editorconfig` / `.gitattributes` / `pom.xml` / `CMakeLists.txt` 编码与行尾声明;`edit` 写盘 >=64 KiB 文件后写穿热预填统一缓存,连改零冷读;扩展闸门 1 常见排版与表情符号替换建议(40+ 字符)及多数行尾智能推荐;新增一站式傻瓜命令 `/charset`(体检)与 `/charset fix`(按多数行尾整批安全修复并支持一次 `/charset-undo` 撤回),以及每会话至多一次的终端 `U+FFFD` 乱码自动提醒。
42
+ - 新增纳秒级 `FileStamp` 16 MiB 解码读缓存(`src/operations.ts`、`src/encoding/file-stamp.ts`,2.2 MiB GBK 缓存读降至 **0.036 ms**、较朴素读解码快 **306×**)、`fastEncodeDbcs`/`fastCanEncodeAll` 纯 ASCII 原生快路径(提速 **14×**)、`restoreLineEndings` 零分配无改动快路径(提速 **7×**)、C++ UTF-16 行尾检测(`src/encoding/line-endings.ts`),以及可复现性能与多编码评测套件 `test/perf/eval-benchmark.test.ts`。
43
+ - 新增受控维护与可观测命令(`src/maintenance.ts`):`/charset-explain <路径>`(完整决策链 + `.editorconfig`/`.gitattributes`/`pom.xml`/`CMakeLists.txt` 项目线索)、`/charset-normalize-eol <路径> --to crlf|lf [--dry-run]`(保持原编码与 BOM 统一混合换行,彻底消除 `dos2unix` 死锁)、`/charset-convert <路径> --to <编码> [--bom|--no-bom] [--dry-run]`(闸门 1/2 预检 + `/charset-undo` 可撤销);为非 UTF-8 文件补充 `read` 元数据与 TUI 编码徽章;统一机器可读错误码(`[GATE1_UNMAPPABLE; not_applied]`、`[MIXED_EOL; not_applied]`、`[STALE_READ; not_applied]` 等)、`locale`(`"auto" | "en" | "zh-CN"`)配置,以及闸门 1 的 `@L<行>:<列>` 定位与常见排版字符安全替代建议。
44
+ - `read(outline=true)` 新增精确起止行范围 `[..endLine]` 与 `offset`/`limit` 分页;`apply_patch` 聚合多文件预检失败以便单轮修齐;零配置新建空子目录支持向上 3 层父目录兄弟推断;`grep` 支持显式 `force: true` 的单字节编码(如 `windows-1252`);新增 IDE 自动补全 Schema(`schema/pi-charset.schema.json`)与团队 CI / Pre-commit 门禁 CLI(`tools/pi-charset-cli.mjs` / `npx pi-charset check --staged --strict-eol`)。
45
+ - 新增 `shellGuard`(`"block"` | `"warn"` | `"off"`,有 `.pi-charset.json` 或零配置命中非 UTF-8 文件/目录时默认 `"block"`),通过 Pi `tool_call` 钩子在命令执行前拦截绕过编码门禁的 Shell 写入与转码(`python -c` 写盘/`chardet`、`iconv`/`dos2unix`、`sed -i`/`perl -pi`、`node -e writeFile*`、PowerShell `Set-Content`/`Out-File`/`[IO.File]::WriteAll*` 及源码重定向),同时放行正常编译、测试、git 与只读脚本。
46
+ - `edit` 工具支持四种编码安全编辑模式(`edits` Search/Replace、`hashlines` 内容哈希行锚定配合改后新锚点回传、OMP 锚点方言、回显前缀吸收、漂移感知 `HASH_MISMATCH` 自纠与 `NOOP_LOOP` 护栏、`patch` 兼容 unified diff / Codex 块 / Aider `SEARCH/REPLACE` 块、以及 `wholeFile` 整文件替换),并新增多文件 `apply_patch` 工具(支持 Codex `*** Begin Patch` 含 `*** Hashline File:`、Aider 多文件 `SEARCH/REPLACE` 与 `diff --git`),具备全有或全无预检、有序多路径无死锁加锁与含新增/删除文件的 `/charset-undo` 撤销能力。
47
+ - 低 Token 视图:`read` 新增 `outline: true`(结构化符号大纲 + `<行号>:<2位hex>|` 锚点,支持多行函数/方法签名、嵌套结构与 C++ 类构造函数,覆盖 C/C++/TS/JS/Python/Java/Go/Rust/SQL/Proto/Lua/Ruby/Elixir/CMake/CSS/Markdown/配置,并免疫多行/嵌套注释、JS/TS 模板字符串、Go/Rust/C++ 原始字符串、Java 文本块、Python 文档字符串与 Markdown 代码围栏)与 `ranges: [[起, 止], ...]`(单次多片段读取,大文件定位与抽读节省 **17×–42×** Token);`grep` 新增 `filesOnly: true`(文件与命中计数发现模式)与 `hashlines: true`(搜索直连编辑)。
48
+ - `/charset-undo`:有界(32 MiB)会话内撤销,支持多文件 `apply_patch` 整批原子撤销(有序多路径加锁,含 `lstat`/可写性/哈希全有或全无预检,完整覆盖更新/新增/删除/重命名),支持 `list`、`b<批次号>` / `batch:<批次号>`、`#<序号>` 与 `<路径>`(不遮蔽名为 `b1`/`12` 的普通文件),并拦截外部修改与乱序撤销。
49
+ - `autoCommit` 选项:通过验证的写入后只把该文件以路径限定提交提交到 git。
50
+
51
+ ### 修复
52
+
53
+ - 对齐 Pi 原生 `read`、`write`、`edit`、`apply_patch`、`grep` 与 `bash`/`powershell` 全量能力:修复 `read` 在 `hashlines`/`outline`/`ranges` 与附注场景下缺失或过期的 `structuredContent`、跳过对 `firstLineExceedsLimit` 截断提示加哈希前缀、为 `read`/`write` 补齐 `file_path` 别名与 macOS NFD/弯引号/AM-PM 路径兼容、兼容 JSON 字符串与单对象形态的 `hashlines`/`ranges`(含显式 `undefined` 键)、将 `NOOP_LOOP` 检测绑定会话 `epoch`、空串替换行时仍回传空行新锚点、展开 `edit` 结果时经 `renderDiff` 着色、`grep` 完整遵循 `ctx.cwd` 与 `~`/`@path` 展开、为 `apply_patch` 补齐 `constrainedSampling` 与 `renderShell: "self"`(及 `Move` 的闸门 2 校验与新锚点回传)、`transcodeBash` 开启时正确透传 `shellPath` 与 `commandPrefix`,并将 `shellGuard` 升级为引号与 heredoc 感知的词法分段器,彻底消除对 `git commit`/`rg`/`echo` 参数的误拦,同时拦截 `bash -c`/`pwsh -Command`/`node -p` 与含引号分号的绕过写法。
54
+ - 修复流式 Shell 转码在前 64 KiB 纯 ASCII 输出后锁死透传导致后续 GBK 编译报错乱码,以及带 BOM 的 UTF-16LE/BE 输出被误按 GB18030 解码的问题;修复 `src/shell.ts` 对 PowerShell `Get-Content` 带值参数的识别并支持按子目录动态刷新 Shell 规则;同步升级 `tools/scan-encoding.mjs` 的损坏 BOM/UTF-32/UTF-16 校验、UTF-16 行尾识别与 CJK 跨家族消歧,避免 `/charset-init` 将 Shift_JIS/Big5/EUC-KR 工程误生成为 GBK。
55
+ - 统一 `classify`、`config`、`siblingInference` 与 `grep` 的缓存失效证据模型(`src/encoding/file-stamp.ts`:`dev`/`ino`/`size`/`mtimeMs`/`ctimeMs`),外部修改/删除 `.pi-charset.json` 时自动递增 `configGeneration()` 并清理兄弟推断;`write`/`edit`/`apply_patch`/`undo` 共用 `invalidatePathCaches` 跨缓存失效路径;将兄弟推断、`rg` 探测、`read`/`/charset-status` 配置读取与 Windows `chcp` 探测移至异步非阻塞热路径;多文件 `grep` 冷命中在 16 MiB 有界缓存内复用已读字节(每文件仅读盘一次);合并去重 `HASH_MISMATCH` 重叠上下文行与编辑输入校验。
56
+ - 修复同一文件多次写入后 `/charset-undo <路径>` 误选中最早记录导致撤销失败的问题,修复 `/charset-undo #<序号>` 误按路径撤销最新记录的问题,将会话撤销日志内存上限定为 32 MiB(仅保留 `afterSha1`/`afterBytes` 不再双倍滞留大缓冲,并整批淘汰过期批次),按仓库串行化 `autoCommit` 并为 `apply_patch` 合并单次原子提交以消除 `.git/index.lock` 竞态,在单文件 `edit(patch)` 中显式拒绝 `*** Move to:`,在 `apply_patch` 中途失败时明确列出已落盘文件与回退批次号,并为 `apply_patch` 补齐 Pi TUI 预览与结果渲染。
57
+ - 对齐带 UTF-8 BOM 文件在 `read(outline)`、`read(hashlines)`、`read(ranges)`、`grep(hashlines)` 与 `edit(hashlines)` 中的第 1 行哈希与大纲识别,写回时完整保留磁盘 BOM。
58
+ - 保留 ripgrep 自动探测带 BOM 的 UTF-16 文件所得的命中,并在含单独 CR 时保持搜索行号一致。
59
+ - 如果编辑结果会被字节分类器判成二进制文件,则在写入前拒绝。
60
+ - 转义后的原文提示仍遵守诊断字节上限。
61
+ - 按实际打包清单校验相对链接,并随包提供两种语言的贡献指南。
62
+ - npm 预发布使用 `next` 标签,GitHub Release 标记为预发布。
63
+ - `write` 遇到硬链接文件时拒绝写入,不再悄悄断开链接,与 `edit` 一致。
64
+ - 零配置模式下,`write` 覆盖任何编码都无法解码的字节时现在会被拒绝。此前按规则的 UTF-8 偏好二次分类会把这些字节标成可解码,并以 UTF-8 覆盖。
65
+ - 零配置模式下读取无法判定的字节时也会给出 UNKNOWN 提示,不再只在有配置时出现。
66
+ - `incompleteUtf8Tail` 严格按 RFC 3629 校验合法前导与续字节,修复流式转码在 `sampleBytes` 处切开多字节 CJK 字符误判为 `unknown`、兄弟推断跨文件拼接破坏多字节边界及 `runRgPass` 的 `stop` 信号监听器泄漏。
67
+ - 按解码后的文本区分 CJK 家族。Big5、Shift_JIS、EUC-JP、EUC-KR 文件此前会被当作 GBK 读取(新文本也以 GBK 写入其中),因为它们同样能按 GBK 往返;没有文字证据的字节现在标记 `crossFamilyAmbiguous`,非 ASCII 写入以 `AMBIGUOUS_ENCODING` 拒绝,直到声明编码。
68
+
69
+ ### 移除
70
+
71
+ - 未使用的辅助函数:`verdictForBuffer`、`planBomBytes`、`detectLineEnding`、`detectLineEndingFromText`、`buildEncodingGroups`、`globDirPrefix`。
72
+
9
73
  ## [0.1.4] - 2026-10-28
10
74
 
11
75
  ### 修复
@@ -0,0 +1,33 @@
1
+ # Contributing
2
+
3
+ English | [简体中文](./CONTRIBUTING.zh-CN.md)
4
+
5
+ ## Prerequisites
6
+
7
+ - Node.js `>= 22.19.0`
8
+ - `ripgrep` (`rg`) available on `PATH` or under `~/.pi/agent/bin/`
9
+
10
+ ## Setup
11
+
12
+ ```bash
13
+ npm ci
14
+ npm run verify
15
+ ```
16
+
17
+ ## Development Guidelines
18
+
19
+ - **Code Comments**: Write concise, factual English comments in source, tooling, and test files. Comment non-obvious invariants, edge cases, and platform semantics rather than restating syntax.
20
+ - **Documentation**: Keep English (`README.md`, `CHANGELOG.md`, `docs/*.md`) and Simplified Chinese (`README.zh-CN.md`, `CHANGELOG.zh-CN.md`, `docs/zh-CN/*.md`) synchronized whenever user-visible behavior, configuration, or CLI options change.
21
+ - **Tests**: Add regression coverage in `test/` for every bug fix or gate behavior change. Avoid committing binary test fixtures; generate byte buffers in `test/fixtures/build.ts` or in-memory within tests.
22
+ - **Verification**: Run `npm run verify` (`typecheck` + `vitest` + `check:release`) before opening a pull request.
23
+
24
+ ## Commit Conventions
25
+
26
+ Follow [Conventional Commits](https://www.conventionalcommits.org/):
27
+ - `feat:` new user-facing capability
28
+ - `fix:` bug fix or encoding safety fix
29
+ - `docs:` documentation updates
30
+ - `test:` test additions or refactors
31
+ - `chore:` build, CI, dependency, or release maintenance
32
+
33
+ For release procedures, see [docs/RELEASING.md](./docs/RELEASING.md).
@@ -0,0 +1,33 @@
1
+ # 参与贡献
2
+
3
+ [English](./CONTRIBUTING.md) | 简体中文
4
+
5
+ ## 环境要求
6
+
7
+ - Node.js `>= 22.19.0`
8
+ - 系统 `PATH` 或 `~/.pi/agent/bin/` 中包含可用的 `ripgrep`(`rg`)
9
+
10
+ ## 本地初始化
11
+
12
+ ```bash
13
+ npm ci
14
+ npm run verify
15
+ ```
16
+
17
+ ## 开发约定
18
+
19
+ - **代码注释**:源码、工具脚本与测试文件统一使用简洁准确的英文注释,仅说明关键不变量、边界条件与跨平台行为差异,不重复解释语法表面含义。
20
+ - **双语文档同步**:凡涉及用户可见行为、配置字段或命令行参数的变更,需同步更新英文文档(`README.md`、`CHANGELOG.md`、`docs/*.md`)与简体中文文档(`README.zh-CN.md`、`CHANGELOG.zh-CN.md`、`docs/zh-CN/*.md`)。
21
+ - **测试要求**:修复缺陷或调整门禁逻辑时需在 `test/` 下补充对应回归测试。仓库不提交二进制测试样本,测试字节流在内存或 `test/fixtures/build.ts` 中构造。
22
+ - **提交前自检**:提交或发起 PR 前请确保 `npm run verify`(`typecheck` + `vitest` + `check:release`)全部通过。
23
+
24
+ ## 提交信息规范
25
+
26
+ 采用 [Conventional Commits](https://www.conventionalcommits.org/zh-hans/) 格式:
27
+ - `feat:` 新增功能
28
+ - `fix:` 缺陷或编码安全修复
29
+ - `docs:` 文档更新
30
+ - `test:` 测试增补或重构
31
+ - `chore:` 构建、CI、依赖或发版维护
32
+
33
+ 版本发布流程请参见 [docs/zh-CN/RELEASING.md](./docs/zh-CN/RELEASING.md)。
package/README.md CHANGED
@@ -19,7 +19,7 @@ English | [简体中文](./README.zh-CN.md)
19
19
 
20
20
  For an existing GBK project, run `/charset-init --dry-run` (or `/charset-init embedded-c --dry-run`) inside Pi to review the suggested rules before generating `.pi-charset.json`. Keep `unmappable: "error"` and `verifyWrite: true`: characters that GBK cannot represent should stop a write rather than turn into `?`.
21
21
 
22
- Use Pi's `read`, `edit`, and `write` tools for source changes. Shell redirection and external formatters bypass this extension. After installation, run `/charset-status`, edit a small tracked file, and inspect the diff in your usual editor before wider use.
22
+ Use Pi's `read`, `edit`, `apply_patch`, and `write` tools for source changes. By default (`"shellGuard": "block"` when `.pi-charset.json` applies, or automatically in zero-config non-UTF-8 directories), `pi-charset` also hooks Pi's `tool_call` event to block accidental shell bypasses (`python -c` file writes/`chardet`, `iconv`, `dos2unix`, `sed -i`, `perl -pi`, `node -e writeFile*`, PowerShell `Set-Content`/`Out-File`/`[IO.File]::WriteAll*`, and source redirects) before execution, steering the agent back to encoding-safe tools (set `"shellGuard": "warn"` or `"off"` to relax). After installation, run `/charset-status`, edit a small tracked file, and inspect the diff in your usual editor before wider use.
23
23
 
24
24
  Byte detection is not proof of an encoding: GBK and GB18030 overlap, and some bytes also decode under other encodings. For a project that requires GBK, declare GBK explicitly instead of relying on inference, especially for new or ASCII-only files. This extension prevents new encoding damage; it cannot reconstruct text that was already saved as question marks or mojibake.
25
25
 
@@ -42,6 +42,18 @@ Files are classified in memory in a fixed order:
42
42
  - **Gate 2 (Pre-Write Round-Trip & Post-Write Read-Back)**: Verifies `decode(encode(text)) === text` in memory before touching disk, then reads back the written file to verify byte and text equality. If post-write verification fails, `pi-charset` reports the mismatch and preserves the on-disk file without rolling back to a stale backup.
43
43
  - **Gate 3 (Unknown & Lossy Conversion Guard)**: Rejects writes to `BINARY` or `UNKNOWN` files, preserves existing `UTF-8` files by default (`protectUtf8: true`), and rejects writes when existing on-disk bytes cannot losslessly round-trip in the target encoding.
44
44
 
45
+ ### Exact edit tool, token-efficient views & multi-file `apply_patch`
46
+
47
+ `edit` supports four encoding-safe editing modes over the same immutable snapshot, shared preview, and Gate 1/2/3 verification: **Search/Replace** (`edits[{oldText,newText}]`), **Hashline** (`hashlines` anchored by `<line>:<2-hex>` tags from `read(hashlines=true)`, `read(outline=true)`, or `grep(hashlines=true)`; returns updated post-edit anchors so follow-up edits require zero re-reads), **Apply Patch** (`patch`: unified diff, Codex hunks, or Aider `<<<<<<< SEARCH / ======= / >>>>>>> REPLACE` blocks), and **Whole File** (`wholeFile`). Multi-file patches (`apply_patch`) support Codex (`*** Begin Patch` with `Update`/`Hashline`/`Add`/`Delete`/`Move`), Aider multi-file `SEARCH/REPLACE`, and `diff --git` with all-or-nothing pre-flight validation and deadlock-free path locks before mutating any file. `read` adds `outline=true` (structural symbols with Hashline anchors) and `ranges=[[start,end],...]` (multi-slice single-pass reads), while `grep` adds `filesOnly=true` discovery and mathematical encodability pass pruning. Total tool schema overhead across all 5 tools stays strictly smaller than Pi's 4 native tools. Whitespace, punctuation, and full-width characters are never silently rewritten; no-ops leave files untouched. See [Edit contract and verification](./docs/EDIT-ENGINE.md).
48
+
49
+ ### Cross-family disambiguation
50
+
51
+ Byte-exact round-trips do not separate CJK families: most Big5, Shift_JIS and EUC-KR text also decodes and re-encodes losslessly as GBK, as different characters. When several families round-trip the same bytes, the extension decodes a sample under each and picks the family whose text is plausible (common and frequent Han characters for Chinese, kana plus common kanji for Japanese, frequent Hangul for Korean). A thin margin marks the bytes `crossFamilyAmbiguous`: `read` shows the best guess with a warning, and `write` or `edit` refuses non-ASCII content with `AMBIGUOUS_ENCODING` until the path has a declared `encoding`. ASCII-only replacements are identical in every family and stay allowed. Declare `encoding` in `.pi-charset.json` to override the decision.
52
+
53
+ ### Undo and git
54
+
55
+ Every verified `write`, `edit`, and `apply_patch` operation is recorded in a bounded (32 MiB) session journal. Multi-file `apply_patch` commits share one batch ID: `/charset-undo` without arguments atomically pre-validates and reverts the entire latest patch batch (including `Update`, `Add`, `Delete`, and `Move`, restoring move sources before removing destinations), or the latest single-file `write`/`edit`. Use `/charset-undo list` to inspect entries, `/charset-undo b<batch>` for a specific batch, `/charset-undo #<id>` for an exact entry, or `/charset-undo <path>` for a single file. Any external modification, deletion, or newer session write on a target file refuses the undo with zero disk mutations, mirroring Aider's `/undo` safety guards. Set `"autoCommit": true` in `.pi-charset.json` to also commit each written file (or an entire `apply_patch` atomically) to git with a path-limited commit, so other staged work stays staged.
56
+
45
57
  ### 3. Line Endings & Baseline Conflict Detection
46
58
 
47
59
  - **Line-Ending Preservation**: Existing files keep their on-disk line endings (`CRLF` or `LF`, detected at the character level for UTF-16); files without newlines do not get trailing newlines appended.
@@ -54,7 +66,7 @@ Files are classified in memory in a fixed order:
54
66
  `pi-charset` works out-of-the-box without requiring a `.pi-charset.json` file:
55
67
  - **Existing Files**: Automatically read in their byte-classified encoding (`GBK`, `GB18030`, `Big5`, `UTF-16`, `UTF-8`) and written back preserving their original encoding, line endings (`CRLF` or `LF`), and BOM.
56
68
  - **New & Pure-ASCII Files**: When no `.pi-charset.json` is present, `pi-charset` inspects sibling files in the same directory (matching extension group first, e.g. `.c`/`.h`) and inherits the dominant encoding and line-ending style (defaulting to `UTF-8` when siblings are UTF-8 or ASCII).
57
- - **Multi-Encoding Search (`grep`)**: Regex patterns and non-ASCII literals run `UTF-8 + GB18030` `ripgrep` passes in zero-config mode, or the configured candidate encodings when `.pi-charset.json` is present. Matches are verified against each file's classified encoding and deduplicated by `file:line`.
69
+ - **Multi-Encoding Search (`grep`)**: The first ripgrep pass searches UTF-8 and detects UTF-16 by BOM. Regex patterns and non-ASCII literals also run a GB18030 pass in zero-config mode, or the configured candidate passes when `.pi-charset.json` is present. Matches are verified against each file's classified encoding and deduplicated by `file:line`. A hit on a pure-ASCII line is exact in every encoding, so it is shown without reading the file — including in text whose encoding cannot be determined.
58
70
 
59
71
  ## Quick Start
60
72
 
@@ -119,12 +131,26 @@ Or create `.pi-charset.json` manually in the project root (JSONC comments suppor
119
131
  }
120
132
  ```
121
133
 
122
- ### 3. Diagnostics
134
+ ### 3. Diagnostics, Recovery & CI Gate
123
135
 
124
- Run inside a Pi session:
136
+ **Zero-config works out of the box** — install once and edit normally (automatically detects GBK/GB18030/Big5/Shift_JIS/EUC-KR/EUC-JP/UTF-16/UTF-8, searches all CJK encodings, and inherits `.editorconfig` / `.gitattributes` / `pom.xml` / `CMakeLists.txt`). When you ever need help, remember just one command: `/charset`:
125
137
 
126
138
  ```text
127
- /charset-status
139
+ /charset # Instant health check ("everything OK" or exact next step)
140
+ /charset fix [path] # Auto-normalize mixed CRLF/LF to majority style (preserves encoding; undoable)
141
+ /charset setup # Auto-generate .pi-charset.json from bytes + project hints
142
+ /charset-undo [list|b<batch>|#<id>|<path>] # Undo the latest write or whole apply_patch / fix batch
143
+ /charset-explain <path> # Full decision trace (bytes, rule/override, BOM/EOL, project hints)
144
+ /charset-convert <path> --to UTF-8 [--bom] # Controlled Gate-1/2 transcoding without disabling shellGuard (undoable)
145
+ ```
146
+
147
+ Run in CI or Git pre-commit hooks (uses the same `.pi-charset.json` rules, plus IDE autocomplete via [schema/pi-charset.schema.json](./schema/pi-charset.schema.json)):
148
+
149
+ ```bash
150
+ npx pi-charset check --staged --strict-eol # Fail CI/pre-commit on damaged bytes, mixed EOL, or encoding drift
151
+ npx pi-charset install-hook --strict-eol # Install managed Git pre-commit gate (worktree-safe)
152
+ npx pi-charset mcp-config # Print Codex / Antigravity / Claude Code MCP config for pi-charset-mcp
153
+ npx pi-charset hints # Show .editorconfig / .gitattributes / pom.xml / CMakeLists.txt hints
128
154
  ```
129
155
 
130
156
  ## Scope & Boundaries
@@ -136,12 +162,13 @@ Run inside a Pi session:
136
162
  | Shell output redirection (`echo >`, `Set-Content`) | No | Bypasses file tools; use `write` or `edit` instead |
137
163
  | CLI startup `@file` arguments | No | Read by the host before extensions load |
138
164
 
139
- Atomic replacement avoids partially written files, but it is not a cross-process transaction or lock. Avoid editing the same file concurrently with external tools. Writes to symbolic links are rejected; edit the target file directly. Existing permission modes are retained, but ownership, ACLs, extended attributes, hard-link relationships, and crash durability are not guaranteed by this replacement scheme.
165
+ Atomic replacement avoids partially written files, but it is not a cross-process transaction or lock. Avoid editing the same file concurrently with external tools. Writes to symbolic links and to files with more than one hard link are rejected, because a replacement would silently break the link; edit the target directly or remove the extra link first. Existing permission modes are retained, but ownership, ACLs, extended attributes, and crash durability are not guaranteed by this replacement scheme.
140
166
 
141
167
  ## Documentation
142
168
 
143
169
  - [Installation Guide](./docs/INSTALL.md)
144
170
  - [Configuration Guide](./docs/CONFIG-GUIDE.md)
171
+ - [Multi-Agent & Same-Core MCP Guide](./docs/MCP-AND-MULTI-AGENT.md)
145
172
  - [Host Compatibility Matrix](./docs/COMPATIBILITY.md)
146
173
  - [Acceptance & Test Matrix](./docs/ACCEPTANCE.md)
147
174
  - [Release Guide](./docs/RELEASING.md)
@@ -161,3 +188,5 @@ npm run verify # Run typecheck + test + check:release
161
188
  ## License
162
189
 
163
190
  [MIT](./LICENSE) © 2026 ethan-blue
191
+
192
+ [Editing plan](docs/EDITING-PLAN.md) · [Implementation and benchmarks](docs/PROGRESS.md) · [Model-task evaluation](docs/MODEL-EVAL.md) · [Design review](docs/DESIGN-REVIEW.md)
package/README.zh-CN.md CHANGED
@@ -19,7 +19,7 @@
19
19
 
20
20
  已有 GBK 工程,建议先在 Pi 中运行 `/charset-init --dry-run`(或嵌入式 C 工程运行 `/charset-init embedded-c --dry-run`),确认建议的目录规则后再生成 `.pi-charset.json`。保留 `unmappable: "error"` 和 `verifyWrite: true`:GBK 放不下的字符应该报错,而不是静默变成问号。
21
21
 
22
- 修改源码时使用 Pi 的 `read`、`edit`、`write` 工具。Shell 重定向和外部格式化工具不经过本扩展。安装后先用 `/charset-status` 查看状态,试改一个已纳入版本管理的小文件,再用常用编辑器核对差异。
22
+ 修改源码时使用 Pi 的 `read`、`edit`、`apply_patch` 与 `write` 工具。默认开启的 **`shellGuard` 防绕过护栏**(存在 `.pi-charset.json` 或零配置命中非 UTF-8 文件/目录时自动生效)会在 Pi 的 `tool_call` 阶段直接拦截模型自发调用的 `python -c` 写盘/`chardet`、`iconv`、`dos2unix`、`sed -i`、`perl -pi`、`node -e writeFile*`、PowerShell `Set-Content`/`Out-File`/`[IO.File]::WriteAll*` 及源码重定向,把修改强制导回编码安全工具(可在 `.pi-charset.json` 设 `"shellGuard": "warn"` 或 `"off"` 放宽)。安装后先用 `/charset-status` 查看状态,试改一个已纳入版本管理的小文件,再用常用编辑器核对差异。
23
23
 
24
24
  字节判定不能证明文件的原始编码。GBK 与 GB18030 存在重叠,同一串字节也可能符合其他编码;工程明确要求 GBK 时,应显式配置 GBK,尤其是新建文件和纯 ASCII 文件。本扩展用于防止新增乱码,不能恢复已经保存为问号或错误文本的原始内容。
25
25
 
@@ -42,6 +42,10 @@
42
42
  - **闸门 2(写前往返与写后回读校验)**:落盘前在内存验证 `decode(encode(text)) === text`;落盘后回读磁盘文件核对字节与解码文本。若写后核对不一致,报错并保留磁盘现状,不执行旧备份回滚。
43
43
  - **闸门 3(未知编码与有损写入拦截)**:拦截 `BINARY` 与 `UNKNOWN` 文件写入;含非 ASCII 的 UTF-8 文件默认保持 UTF-8 写回(`protectUtf8: true`);磁盘原字节无法在目标编码下逐字节无损回环时拒绝写入。
44
44
 
45
+ ### 精确编辑、低 Token 视图与多文件 `apply_patch`
46
+
47
+ `edit` 在同一不可变快照、共享预览与三道写入门禁之上支持四种编码安全编辑模式:**Search/Replace**(`edits[{oldText,newText}]`)、**Hashline**(`hashlines`,配合 `read(hashlines=true)`、`read(outline=true)` 或 `grep(hashlines=true)` 返回的 `<行号>:<2位十六进制>` 锚点,修改后自动回传新锚点与行偏移,连续编辑免重读)、**Apply Patch**(`patch`,支持标准 unified diff、Codex 块及 Aider `<<<<<<< SEARCH / ======= / >>>>>>> REPLACE` 块)与 **Whole File**(`wholeFile`)。跨多文件工具 `apply_patch` 兼容 Codex(`*** Begin Patch`,支持 `Update`/`Hashline`/`Add`/`Delete`/`Move`)、Aider 多文件 `SEARCH/REPLACE` 与 `diff --git`,先完成全有或全无预检与有序多路径加锁后再原子落盘。`read` 支持 `outline=true`(结构化符号大纲 + 哈希锚点)与 `ranges=[[起,止],...]`(单次多片段精准读取),`grep` 支持 `filesOnly=true` 文件级发现与基于字符集可编码性的搜索趟数学剪枝;全部 5 个工具的每轮 Schema 开销严格低于 Pi 原生 4 工具。全链路绝不静默模糊改写缩进、标点或全角字符,原样替换不写盘。详见[编辑契约与验收](./docs/zh-CN/EDIT-ENGINE.md)。
48
+
45
49
  ### 3. 行尾与读取基线校验
46
50
 
47
51
  - **行尾保持**:已存在文件按磁盘原有行尾(`CRLF` 或 `LF`,UTF-16 按解码后字符级识别)写回;无换行文件不追加尾部换行。
@@ -49,12 +53,20 @@
49
53
  - **新建文件行尾**:支持通过 `newFileLineEnding: "CRLF" | "LF"` 指定新建文件的行尾格式。
50
54
  - **读取基线冲突检测**:读取文件时记录 SHA-1 指纹;写入前若磁盘内容被外部修改或删除,报冲突并拒绝覆盖。
51
55
 
56
+ ### 跨编码家族消歧
57
+
58
+ 字节级无损往返并不能区分 CJK 家族:大多数 Big5、Shift_JIS 和 EUC-KR 文本同样能按 GBK 无损解码再编码,只是变成另外的字。当多个家族对同一批字节都能往返时,扩展会对每种家族解码一段样本,选择文本最合理的家族(中文看常用与高频汉字,日文看假名与常用汉字,韩文看高频谚文)。差距过小时标记为 `crossFamilyAmbiguous`:`read` 按最佳猜测显示并给出警告,`write` 与 `edit` 拒绝含非 ASCII 的内容并返回 `AMBIGUOUS_ENCODING`,直到该路径声明了 `encoding`。纯 ASCII 替换在任何家族下都相同,始终允许。在 `.pi-charset.json` 中声明 `encoding` 可覆盖判定。
59
+
60
+ ### 撤销与 git
61
+
62
+ 每次通过验证的 `write`、`edit` 与 `apply_patch` 都会记入有界(32 MiB)会话日志。多文件 `apply_patch` 的全部文件操作共享同一批次号:不带参数的 `/charset-undo` 会先对整批文件做全有或全无预检,再原子撤销整批改动(涵盖 `Update`、`Add`、`Delete` 与 `Move`,先恢复重命名源文件再移除目标文件),单文件写入则撤销最近一条。支持 `/charset-undo list` 查看记录、`/charset-undo b<批次号>` 撤销指定批次、`/charset-undo #<序号>` 精确撤销单条、`/charset-undo <路径>` 撤销单个文件;若目标文件其后被外部修改、删除或存在更新的会话写入,直接拒绝且不改动磁盘,与 Aider 的 `/undo` 护栏一致。在 `.pi-charset.json` 中设置 `"autoCommit": true` 可在写入后把本次改动文件(或多文件 `apply_patch` 整体)以路径限定提交到 git,用户已暂存的其他改动不受影响。
63
+
52
64
  ### 4. 零配置自适应与同目录邻居推断
53
65
 
54
66
  `pi-charset` 安装后无需编写 `.pi-charset.json` 即可直接工作:
55
67
  - **已存在文件**:读取时按文件自身字节判定出的编码(`GBK`、`GB18030`、`Big5`、`UTF-16`、`UTF-8`)解码;写入时自动保持原文件编码、原有行尾(`CRLF` 或 `LF`)与 BOM。
56
68
  - **新建文件与纯 ASCII 文件加中文**:未放置 `.pi-charset.json` 时,自动扫描同目录下的相邻源码文件(优先匹配同语言后缀族,如 `.c`/`.h`),继承该目录的主流编码与行尾格式(同目录为 UTF-8 或空目录时默认 `UTF-8`)。
57
- - **多编码搜索(`grep`)**:正则搜索或非 ASCII 字面量搜索时,零配置下执行 `UTF-8 + GB18030` 双趟 `ripgrep` 搜索(有 `.pi-charset.json` 时按配置候选编码集合分趟),经逐文件字节判定复核后按 `file:line` 去重。
69
+ - **多编码搜索(`grep`)**:ripgrep 首趟搜索 UTF-8,并通过 BOM 自动识别 UTF-16。正则或非 ASCII 字面量搜索在零配置下追加 GB18030 搜索趟,有 `.pi-charset.json` 时按配置候选编码分趟。命中经文件字节判定复核后按 `file:line` 去重。纯 ASCII 行上的命中在任何编码下都相同,因此无需读取文件即可显示——编码无法判定的文本也不例外。
58
70
 
59
71
  ## 快速开始
60
72
 
@@ -119,12 +131,26 @@ node tools/scan-encoding.mjs /path/to/project --init
119
131
  }
120
132
  ```
121
133
 
122
- ### 3. 状态诊断
134
+ ### 3. 一键体检、自动修复与 CI 门禁
123
135
 
124
- 在 Pi 会话中执行:
136
+ **安装即忘、零配置直接生效**——自动识别并保真读写 GBK/GB18030/Big5/Shift_JIS/EUC-KR/EUC-JP/UTF-16/UTF-8,零配置全东亚多编码搜索,并自动继承 `.editorconfig` / `.gitattributes` / `pom.xml` / `CMakeLists.txt`。只需记住一个命令 `/charset`:
125
137
 
126
138
  ```text
127
- /charset-status
139
+ /charset # 一键体检(一切正常无需配置,或直接给出一步修复指令)
140
+ /charset fix [路径] # 按各文件多数行尾一键修混合换行(原编码与 BOM 不变,可一键撤回)
141
+ /charset setup # 自动融合字节与项目声明生成 .pi-charset.json
142
+ /charset-undo [list|b<批次号>|#<序号>|<路径>] # 撤销最近一次写入或整批 apply_patch / fix
143
+ /charset-explain <路径> # 解释字节判定、命中 override、BOM/EOL 与项目线索
144
+ /charset-convert <路径> --to UTF-8 [--bom] # 带闸门 1/2 预检的受控转码(可撤销,无需关 shellGuard)
145
+ ```
146
+
147
+ 在 CI 或 Git pre-commit 中复用同一份 `.pi-charset.json` 规则做团队门禁(同时提供 [schema/pi-charset.schema.json](./schema/pi-charset.schema.json) 供 IDE 自动补全与校验):
148
+
149
+ ```bash
150
+ npx pi-charset check --staged --strict-eol # 拦截损坏字节、混合换行或编码漂移
151
+ npx pi-charset install-hook --strict-eol # 一键安装 Git pre-commit 编码质检钩子(自动兼容 git worktree)
152
+ npx pi-charset mcp-config # 输出 Codex / Antigravity / Claude Code 的 pi-charset-mcp 配置
153
+ npx pi-charset hints # 读取 .editorconfig / .gitattributes / pom.xml / CMakeLists.txt 线索
128
154
  ```
129
155
 
130
156
  ## 作用边界
@@ -136,12 +162,13 @@ node tools/scan-encoding.mjs /path/to/project --init
136
162
  | Shell 重定向写文件(如 `echo >`、`Set-Content`) | 否 | 不经过文件工具层,请使用 `write` 或 `edit` 工具写文件 |
137
163
  | 启动命令行 `@file` 参数 | 否 | 在扩展加载前由宿主直接读取 |
138
164
 
139
- 原子替换用于避免文件只写了一半,不等于跨进程事务或文件锁。请避免与外部工具同时修改同一文件。符号链接拒绝写入,请直接修改目标文件。替换时保留已有权限模式,但不保证保留所有者、ACL、扩展属性、硬链接关系,也不保证掉电后的持久性。
165
+ 原子替换用于避免文件只写了一半,不等于跨进程事务或文件锁。请避免与外部工具同时修改同一文件。符号链接和带多个硬链接的文件拒绝写入,因为替换会悄悄断开硬链接;请直接修改目标文件或先解除多余的硬链接。替换时保留已有权限模式,但不保证保留所有者、ACL、扩展属性,也不保证掉电后的持久性。
140
166
 
141
167
  ## 文档索引
142
168
 
143
169
  - [安装说明](./docs/zh-CN/INSTALL.md)
144
170
  - [配置指南](./docs/zh-CN/CONFIG-GUIDE.md)
171
+ - [多工具协同与同源 MCP 指南](./docs/zh-CN/MCP-AND-MULTI-AGENT.md)
145
172
  - [宿主兼容矩阵](./docs/zh-CN/COMPATIBILITY.md)
146
173
  - [验收与测试矩阵](./docs/zh-CN/ACCEPTANCE.md)
147
174
  - [发布规范](./docs/zh-CN/RELEASING.md)
@@ -161,3 +188,5 @@ npm run verify # 依次运行 typecheck + test + check:release
161
188
  ## 许可证
162
189
 
163
190
  [MIT](./LICENSE) © 2026 ethan-blue
191
+
192
+ [编辑引擎原方案](docs/zh-CN/EDITING-PLAN.md) · [实施进度与基准](docs/zh-CN/PROGRESS.md) · [模型任务对照](docs/zh-CN/MODEL-EVAL.md) · [设计复审](docs/zh-CN/DESIGN-REVIEW.md)
@@ -42,7 +42,22 @@ The matrix below maps expected behavior to test suites; it is not a live CI repo
42
42
  | A-21 | Sub-session tool inheritance | N/A | Host-dependent; documented in [`README.md`](../README.md) scope table |
43
43
  | A-22 | Load `src/index.ts` via `discoverAndLoadExtensions` and CLI RPC mode | PASS | `test/host-integration.test.ts` |
44
44
  | A-23 | Compute encoding-aware `edit` preview diffs and invalidate preview cache | PASS | `test/edit-preview.test.ts` |
45
- | A-24 | Verify `npm pack --dry-run` file whitelist and clean directory loading | PASS | `tools/check-release.mjs` |
45
+ | A-24 | Verify npm package contents and links, then load the installed package in a clean directory | PASS | `tools/check-release.mjs` and the [candidate acceptance record](PROGRESS.md) |
46
+ | A-25 | Resolve every edit against one snapshot with a unique exact match; reject ambiguous (including overlapping) occurrences and overlapping ranges before any write | PASS | `test/edit-plan.test.ts`, contract in [`EDIT-ENGINE.md`](EDIT-ENGINE.md) |
47
+ | A-26 | Use one plan for preview and execution; reject a stale preview or changed arguments with `STALE_PLAN` | PASS | `test/edit-preview.test.ts`, `test/edit-transaction.test.ts` |
48
+ | A-27 | Scope the observed version to the session: external changes after a model-visible read fail with `STALE_READ`; preview and internal reads never refresh it | PASS | `test/edit-preview.test.ts`, `test/edit-transaction.test.ts` |
49
+ | A-28 | Preserve encoding, BOM, line endings, EOF and untouched bytes across UTF-8 BOM, GBK, GB18030 and UTF-16LE/BE edits; reject unencodable or binary-classifying output and empty whole bodies without touching bytes | PASS | `test/edit-transaction.test.ts`, `test/roundtrip.test.ts` |
50
+ | A-29 | Recheck identity and bytes before replacement and read back afterwards; report `TEMP_WRITE_FAILED`, `VERIFY_FAILED` and `COMMIT_UNKNOWN` with commit state and never roll back | PASS | `test/edit-transaction.test.ts`, `test/edit-win-lock.test.ts` |
51
+ | A-30 | Reject symbolic links, hard links and read-only targets for `edit` and `write` with original bytes intact | PASS | `test/edit-transaction.test.ts`, `test/regressions.test.ts` |
52
+ | A-31 | Return bounded diagnostics from actual source within 4 KiB, including JSON-escaped text | PASS | `test/edit-plan.test.ts` |
53
+ | A-32 | Compare native `edit` and pi-charset on model-driven tasks over a mixed-encoding corpus | PASS | `test/eval/` harness and raw records; results in [`MODEL-EVAL.md`](MODEL-EVAL.md) |
54
+ | A-33 | In zero-config mode, undecodable bytes stay `unknown`: `read` reports the UNKNOWN notice and both `edit` and `write` refuse | PASS | `test/zero-config.test.ts` |
55
+ | A-34 | Sibling inference gives the same encoding and line ending as the exhaustive candidate list, is cached per directory, and is recomputed when a sibling changes | PASS | `test/zero-config.test.ts` |
56
+ | A-35 | Show a pure-ASCII hit line without reading the file, also in undecodable text; never surface binary files | PASS | `test/grep.test.ts` |
57
+ | A-36 | Tell CJK families apart by the decoded text: Big5, GBK, Shift_JIS, EUC-JP and EUC-KR files are read in their own encoding in zero-config mode, including short comments and files with mixed scripts | PASS | `test/family.test.ts`, `test/classify.test.ts` |
58
+ | A-37 | Mark bytes with no script evidence `crossFamilyAmbiguous`: warn on read, refuse non-ASCII `write`/`edit` with `AMBIGUOUS_ENCODING`, allow ASCII replacements, honour a declared `encoding` | PASS | `test/family.test.ts` |
59
+ | A-38 | Journal every verified write and undo it with `/charset-undo`, restoring the exact prior bytes, removing created files, refusing when the file changed or disappeared, and keeping the observed version in step | PASS | `test/undo.test.ts`, command registration in `test/host-integration.test.ts` |
60
+ | A-39 | With `autoCommit`, commit only the written file to git and leave other staged work staged; a failed commit becomes a note, never a write failure | PASS | `test/undo.test.ts` |
46
61
 
47
62
  ## 2. Test Suite Breakdown
48
63
 
@@ -59,7 +74,10 @@ The matrix below maps expected behavior to test suites; it is not a live CI repo
59
74
  | `test/line-endings.test.ts` | `CRLF`, `LF`, `MIXED`, and `NONE` detection and restoration |
60
75
  | `test/operations.test.ts` | `read`/`write`/`edit` operations, `newFileLineEnding`, mixed line-ending guard, SHA-1 baseline check |
61
76
  | `test/grep.test.ts` | Multi-pass search, per-file classification filtering, context decoding, zero-config multi-encoding search |
62
- | `test/edit-preview.test.ts` | Synchronous preview routing cache, async diff rendering for GB files, single-byte `force` routing |
77
+ | `test/edit-preview.test.ts` | Shared preview and execution plan, stale plan and stale read rejection, latest-arguments-only rendering |
78
+ | `test/edit-plan.test.ts` | Pure exact planning: uniqueness with overlapping occurrences, batch overlap, CRLF mapping, no-op versus explicit EOF change, bounded diagnostics, 100 shuffled batches against an independent splice |
79
+ | `test/edit-transaction.test.ts` | Byte-level edit safety across encodings, BOM and EOF preservation, whole-body deletion, links and read-only targets, session snapshots, cancellation and commit fault injection |
80
+ | `test/edit-win-lock.test.ts` | Native Windows sharing violation outlasting retries (Windows only) |
63
81
  | `test/shell.test.ts` | Streaming shell output transcoding, split multi-byte chunks, incomplete UTF-8 tail detection, file dump detection |
64
82
  | `test/sysnote.test.ts` | Conditional system prompt injection and `tool_result` notice queue |
65
83
  | `test/zero-config.test.ts` | Zero-config self-adaptive read, write, edit, and same-directory sibling inference |
@@ -68,3 +86,13 @@ The matrix below maps expected behavior to test suites; it is not a live CI repo
68
86
  | `test/host-integration.test.ts` | Extension registration, `/charset-status` + `/charset-init` + `/charset-scan` scaffolding commands, and `discoverAndLoadExtensions` loader test |
69
87
  | `test/perf/io-latency.test.ts` | 300x 8.7KB GBK read/write loop and 1MB file read/write latency |
70
88
  | `test/perf/grep-scale.test.ts` | 2,000-file mixed GBK/UTF-8 search and `AbortSignal` cancellation latency |
89
+ | `test/perf/grep-mismatched-pass.test.ts`, `test/perf/search-tree.test.ts` | Wrong-pass regex rejection with GBK context and line numbers, child-process teardown, opt-in timing probes |
90
+ | `test/perf/grep-hits.test.ts` | Per-hit file access: hits across many GBK files, ASCII-line identifier search and one deep hit in a large file, warm and cold classifier; opt-in timings with `CHARSET_HITS_TIMINGS`
91
+ | `test/perf/read-zero-config.test.ts` | Zero-config read path: legacy file, ASCII file among legacy siblings, directory cache, read-plus-edit; opt-in timings with `CHARSET_READ_TIMINGS` |
92
+ | `test/perf/grep-native-vs-charset.test.ts` | Opt-in side-by-side of the native and encoding-aware grep on identical UTF-8 and GBK trees (`CHARSET_NATIVE_VS`): latency, hit counts, U+FFFD and Chinese shown; asserts only the extension's results |
93
+ | `test/edit-modes.test.ts` | Four commercial editing modes (Hashline, Search/Replace + Aider blocks, single/multi-file Apply Patch in Codex & unified diff formats, Whole File), 100-trial Hashline permutation invariance, 100-trial unified-diff round-trip parity, all-or-nothing multi-file pre-flight & deadlock-free locking |
94
+ | `test/invariants.test.ts` | Exhaustive DFA round-trip proof (231k byte sequences), BMP encodability proof (655k checks), RFC 3629 incomplete UTF-8 tail proof, 200-trial windowed-diff byte-parity test, and property tests for historical bug fixes |
95
+ | `test/family.test.ts` | Cross-family disambiguation for all five CJK families, ambiguity refusal and ASCII allowance, declared override, sibling inference by family, Big5 edit round trip |
96
+ | `test/undo.test.ts` | Session undo journal: restore after write and edit, remove created files, refusal guards, observed-version update, path-limited auto-commit and its failure notice |
97
+ | `test/perf/edit-engine.bench.test.ts`, `test/perf/edit-engine-phases.bench.test.ts` | Opt-in 36-scenario edit benchmark and per-stage timings (`CHARSET_BENCH_OUT`, `CHARSET_PHASES_OUT`); raw samples under `test/perf/results/` |
98
+ | `test/eval/` | Paired model-task harness, frozen task set, corpus provenance and raw records for the native versus pi-charset comparison; run with Node, not vitest |
@@ -10,13 +10,18 @@ English | [简体中文](./zh-CN/COMPATIBILITY.md)
10
10
 
11
11
  | Environment | Host Version | Typecheck | Full Test Suite | Extension Loader (`discoverAndLoadExtensions`) | CLI Smoke (`pi --mode rpc`) |
12
12
  |---|---|---|---|---|---|
13
+ | v0.1.5-rc.1 working tree, Windows 11 / Node 24.18.0 | `0.84.0`, `1.4.0`, `1.7.0` | PASS | 354 passed, 6 skipped per host | PASS | PASS on `1.4.0` from the installed tarball |
14
+ | v0.1.5-rc.1 candidate, Windows 11 / Node 22.23.4 | `1.4.0` | PASS | 325 passed, 6 skipped | PASS | — |
15
+ | v0.1.5-rc.1 working tree, Windows 11 / Node 24.18.0, global install | `1.8.0` | PASS | 354 passed, 6 skipped | PASS | PASS (`charset-status`, `charset-init`, `charset-undo`, `charset-scan` via RPC); also the host for the 720-run model evaluation |
16
+ | v0.1.5-rc.1 `ab27a68`, GitHub Actions `ubuntu-latest` / Node 22, 24 | `0.84.0`, `1.4.0`, `1.7.0` | PASS | 354 passed, 6 skipped per job; POSIX mode and symlink cases executed | PASS | — |
17
+ | v0.1.5-rc.1 `ab27a68`, GitHub Actions `windows-latest` / Node 22, 24 | `1.4.0`, `1.7.0` | PASS | 354 passed, 6 skipped per job | PASS | — |
13
18
  | v0.1.2 lockfile, Windows / Node 24 | `1.4.0` | PASS | 271 passed, 2 POSIX-only tests skipped | PASS | — |
14
19
  | v0.1.1 lockfile, Windows / Node 24 | `1.4.0` | PASS | 270 passed, 2 POSIX-only tests skipped | PASS | — |
15
20
  | Historical v0.1.0 lockfile | `0.84.3` | PASS | PASS | PASS | — |
16
21
  | Local Host Junction | `1.2.0` / `1.2.0` / `1.2.0` / `1.2.0` | PASS | PASS | PASS | PASS |
17
22
  | Clean Tarball Unpack | `1.4.0` | — | — | PASS | — |
18
23
 
19
- See GitHub Actions for current Windows/Linux and Node 22/24 results.
24
+ The `ab27a68` rows come from [CI run 47492178717](https://github.com/ethan-blue/pi-charset/actions/runs/47492178717), which exercises every job in `.github/workflows/ci.yml`; the first hosted run of the candidate was [47277976527](https://github.com/ethan-blue/pi-charset/actions/runs/47277976527) at `8f9e98e`. On-demand timing runs live in `.github/workflows/bench.yml` (see the progress record). The one-test difference between operating systems is the Windows-only sharing-lock case against the two POSIX-only cases in `test/regressions.test.ts`.
20
25
 
21
26
  The root `overrides` entry keeps the checkout's host dependency on a patched `undici`. npm ignores dependency-package overrides when this extension is installed into another application: update and audit your actual Pi installation separately.
22
27
 
@@ -4,6 +4,8 @@ English | [简体中文](./zh-CN/CONFIG-GUIDE.md)
4
4
 
5
5
  ---
6
6
 
7
+ **Exact edit:** `edit` keeps the detected encoding and original BOM and always verifies written bytes. Explicit whole-file conversion, `unmappable` fallbacks, and `verifyWrite: false` belong to `write`, not `edit`. For pure ASCII targets, `edit` can adopt the configured or inferred scope encoding only when existing bytes remain identical. See [the edit contract](./EDIT-ENGINE.md).
8
+
7
9
  ## 1. Quick Initialization & Scaffolding
8
10
 
9
11
  Inside a Pi session, scaffold `.pi-charset.json` directly without looking up package paths (updates take effect immediately without restarting Pi):
@@ -40,7 +42,7 @@ node tools/scan-encoding.mjs D:/path/to/project --init
40
42
  When no `.pi-charset.json` is present up the directory tree, `pi-charset` operates in **zero-config self-adaptive mode**:
41
43
  - **Existing Files**: `read`, `write`, and `edit` classify each file by its bytes. Existing `GBK`, `GB18030`, `Big5`, `UTF-16`, and `UTF-8` files are decoded to UTF-8 on read and written back in their original encoding, line-ending style (`CRLF` or `LF`), and BOM, with all three write safety gates active.
42
44
  - **New & Pure-ASCII Files**: `pi-charset` scans up to 16 sibling files in the same directory (prioritizing the same file extension group such as `.c`/`.h`) and inherits the dominant encoding and line ending (defaulting to `UTF-8` if no CJK siblings exist).
43
- - **Multi-Encoding `grep`**: Regex patterns and non-ASCII literals run across `UTF-8` and `GB18030` passes and deduplicate matches by `file:line`. ASCII-only regexes also need these passes: for example, `\p{Han}` matches Chinese characters despite containing only ASCII syntax.
45
+ - **Multi-Encoding `grep`**: The first pass searches UTF-8 and detects UTF-16 by BOM. Zero-config searches add a GB18030 pass for regex and non-ASCII literals, then deduplicate by `file:line`. Hits on pure-ASCII lines need no classification or file access. ASCII-only regexes can also match legacy text, for example when using `\p{Han}`.
44
46
  - `.pi-charset.json` is only needed when you want to override defaults (e.g., strict GBK enforcement for new/ASCII files, single-byte `ISO-8859-1` with `force: true`, explicit encoding migration, or enabling `transcodeBash`).
45
47
 
46
48
  ## 3. Configuration Reference
@@ -57,6 +59,7 @@ When no `.pi-charset.json` is present up the directory tree, `pi-charset` operat
57
59
  | `newFileLineEnding` | `undefined` | Line-ending style for newly created files (`"CRLF"` or `"LF"`). Does not alter existing files. |
58
60
  | `transcodeBash` | `false` | Shell output transcoding: `false` (disabled), `true` / `"auto"`, or an explicit encoding name (e.g., `"GBK"`). Requires restarting Pi when changed. |
59
61
  | `bashFileDump` | `true` | When `transcodeBash` is enabled, single-file dump commands (`type`, `cat`, `head`, `tail`, `Get-Content`) use the file's own read encoding. |
62
+ | `autoCommit` | `false` | Opt-in: after a verified `write` or `edit`, `git add` and `git commit` only that file (Aider-style). Needs the file inside a git work tree; failures become notes, never write failures. |
60
63
  | `overrides` | `[]` | Path-based glob override rules. |
61
64
 
62
65
  ### Choosing an Unmappable-Character Policy