pi-charset 0.1.5 → 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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ 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
+
10
24
  ## [0.1.5] - 2026-12-06
11
25
 
12
26
  ### Changed
@@ -6,6 +6,20 @@
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
+
9
23
  ## [0.1.5] - 2026-12-06
10
24
 
11
25
  ### 变更
package/README.md CHANGED
@@ -148,6 +148,8 @@ Run in CI or Git pre-commit hooks (uses the same `.pi-charset.json` rules, plus
148
148
 
149
149
  ```bash
150
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
151
153
  npx pi-charset hints # Show .editorconfig / .gitattributes / pom.xml / CMakeLists.txt hints
152
154
  ```
153
155
 
@@ -166,6 +168,7 @@ Atomic replacement avoids partially written files, but it is not a cross-process
166
168
 
167
169
  - [Installation Guide](./docs/INSTALL.md)
168
170
  - [Configuration Guide](./docs/CONFIG-GUIDE.md)
171
+ - [Multi-Agent & Same-Core MCP Guide](./docs/MCP-AND-MULTI-AGENT.md)
169
172
  - [Host Compatibility Matrix](./docs/COMPATIBILITY.md)
170
173
  - [Acceptance & Test Matrix](./docs/ACCEPTANCE.md)
171
174
  - [Release Guide](./docs/RELEASING.md)
package/README.zh-CN.md CHANGED
@@ -148,6 +148,8 @@ node tools/scan-encoding.mjs /path/to/project --init
148
148
 
149
149
  ```bash
150
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 配置
151
153
  npx pi-charset hints # 读取 .editorconfig / .gitattributes / pom.xml / CMakeLists.txt 线索
152
154
  ```
153
155
 
@@ -166,6 +168,7 @@ npx pi-charset hints # 读取 .editorconfig / .gita
166
168
 
167
169
  - [安装说明](./docs/zh-CN/INSTALL.md)
168
170
  - [配置指南](./docs/zh-CN/CONFIG-GUIDE.md)
171
+ - [多工具协同与同源 MCP 指南](./docs/zh-CN/MCP-AND-MULTI-AGENT.md)
169
172
  - [宿主兼容矩阵](./docs/zh-CN/COMPATIBILITY.md)
170
173
  - [验收与测试矩阵](./docs/zh-CN/ACCEPTANCE.md)
171
174
  - [发布规范](./docs/zh-CN/RELEASING.md)
@@ -0,0 +1,111 @@
1
+ # Multi-Agent Collaboration & Same-Core MCP (`pi-charset-mcp`)
2
+
3
+ English | [简体中文](./zh-CN/MCP-AND-MULTI-AGENT.md)
4
+
5
+ When a team maintains a permanent legacy-encoded codebase (such as GBK embedded C/H firmware or legacy Java) across **Pi**, **Codex**, **Antigravity**, and **Claude Code**, mixing different third-party encoding tools causes subtle rule drift and silent corruption.
6
+
7
+ `pi-charset` solves this with **one shared core, two runtime form factors, and one Git commit gate** reading the same repository `.pi-charset.json`:
8
+
9
+ 1. **Native Pi Extension (`src/index.ts`)**: Runs in-process with zero MCP overhead and full `shellGuard` interception.
10
+ 2. **Same-Core Stdio MCP Server (`pi-charset-mcp`)**: Exposes the exact same deterministic byte classifier, Gate 1/2/3 write protection, SHA-1 read baselines, Windows atomic retry replacement, 4 edit modes, multi-file `apply_patch`, multi-encoding `grep`, controlled EOL/encoding repair, and session undo to **Codex**, **Antigravity**, **Claude Code**, and **Cursor** — with **zero external MCP SDK dependencies** and **no Pi installation required**.
11
+ 3. **Git Pre-Commit Encoding Gate (`pi-charset install-hook`)**: Blocks any commit that introduces damaged bytes, mixed CRLF/LF, or encoding drift even if an agent bypasses tools via shell commands.
12
+
13
+ ---
14
+
15
+ ## 1. Quick MCP Setup (Zero `.pi-charset.json` Required)
16
+
17
+ **No `.pi-charset.json` file is required in your repository.** `pi-charset-mcp` runs in zero-config adaptive mode out of the box (byte classification + 3-level sibling inference + `.editorconfig`/`.gitattributes`/`pom.xml`/`CMakeLists.txt` auto-inheritance + multi-CJK `grep`).
18
+
19
+ If you want to pin defaults for a strict GBK repo **without adding a `.pi-charset.json` file**, pass CLI flags (`--encoding GBK --eol CRLF --prefer-legacy --hashlines --auto-commit`) or `PI_CHARSET_*` environment variables directly to `pi-charset-mcp`.
20
+
21
+ Print ready-to-paste snippets or one-command installs:
22
+
23
+ ```bash
24
+ npx pi-charset mcp-config --client codex
25
+ npx pi-charset mcp-config --client codex --encoding GBK --eol CRLF --prefer-legacy
26
+ npx pi-charset mcp-config --client antigravity
27
+ npx pi-charset mcp-config --client claude
28
+ ```
29
+
30
+ ### Codex (one-command CLI or `~/.codex/config.toml`)
31
+
32
+ ```bash
33
+ # Zero-config (no .pi-charset.json needed)
34
+ codex mcp add pi-charset -- npx -y -p pi-charset pi-charset-mcp
35
+
36
+ # Or pin GBK + CRLF + short-header protection via CLI flags (still zero JSON files in repo)
37
+ codex mcp add pi-charset -- npx -y -p pi-charset pi-charset-mcp --encoding GBK --eol CRLF --prefer-legacy
38
+ ```
39
+
40
+ ### Antigravity / Cursor / Windsurf (`mcp_config.json`)
41
+
42
+ ```json
43
+ {
44
+ "mcpServers": {
45
+ "pi-charset": {
46
+ "command": "npx",
47
+ "args": ["-y", "-p", "pi-charset", "pi-charset-mcp"]
48
+ }
49
+ }
50
+ }
51
+ ```
52
+
53
+ ### Claude Code
54
+
55
+ ```bash
56
+ claude mcp add pi-charset -- npx -y -p pi-charset pi-charset-mcp
57
+ ```
58
+
59
+ ---
60
+
61
+ ## 2. Exposed MCP Tools
62
+
63
+ All 7 tools share one in-memory session `ReadScope` (SHA-1 read baselines + bounded undo journal + nanosecond-stamped content cache):
64
+
65
+ | Tool | Purpose |
66
+ | --- | --- |
67
+ | `charset_read` | Encoding-safe read with `outline`, `ranges`, `offset`/`limit`, `hashlines`, and SHA-1 baseline recording |
68
+ | `charset_write` | Full-file write through Gate 1/2/3, atomic Windows retry replace, SHA-1 conflict check, and undo |
69
+ | `charset_edit` | Exact edit supporting `edits` (S/R), `hashlines`, `patch`, and `wholeFile` (returns updated Hashline anchors) |
70
+ | `charset_apply_patch` | Atomic pre-validated multi-file patch (`*** Begin Patch`, Aider S/R, or unified diff) with batch undo |
71
+ | `charset_grep` | Multi-encoding ripgrep (`UTF-8`, `GB18030`, `GBK`, `Big5`, `Shift_JIS`, `EUC-KR`, `EUC-JP`, `UTF-16`) |
72
+ | `charset_check` | Read-only file rule trace (`path` provided) or workspace health scan (`path` omitted) |
73
+ | `charset_fix` | Controlled `normalize_eol`, `auto_fix_eol`, `convert`, and `undo` without touching shell scripts |
74
+
75
+ ---
76
+
77
+ ## 3. Locking Down Short GBK Headers (`preferSourceOverUtf8`)
78
+
79
+ In rare cases, a very short BOM-less GBK file (for example a tiny `.h` header containing only a few Chinese characters whose bytes happen to satisfy 3-byte UTF-8 grammar) can pass strict `isUtf8` before GBK round-trip testing.
80
+
81
+ In strictly GBK-locked source trees, set `"preferSourceOverUtf8": true` on the root or per-directory override in `.pi-charset.json`:
82
+
83
+ ```jsonc
84
+ {
85
+ "$schema": "./node_modules/pi-charset/schema/pi-charset.schema.json",
86
+ "sourceEncoding": "GBK",
87
+ "writeEncoding": "GBK",
88
+ "protectUtf8": true,
89
+ "preferSourceOverUtf8": true,
90
+ "transcodeBash": "auto",
91
+ "newFileLineEnding": "CRLF",
92
+ "overrides": [
93
+ { "pattern": "docs/**", "encoding": "UTF-8", "preferSourceOverUtf8": false, "newFileLineEnding": "LF" }
94
+ ]
95
+ }
96
+ ```
97
+
98
+ Files carrying a UTF-8 BOM or non-GBK UTF-8 sequences continue to classify safely as UTF-8, while BOM-less files whose bytes are valid GBK stay locked as GBK.
99
+
100
+ ---
101
+
102
+ ## 4. Parallel Multi-Agent Workflow (`git worktree` + Pre-Commit Gate)
103
+
104
+ 1. **Isolate concurrent agents with `git worktree`**: Give Pi, Codex, and Antigravity separate worktrees (for example main checkout for Keil + Pi, secondary worktree for Codex/Antigravity) so concurrent edits never collide on SHA-1 read baselines.
105
+ 2. **Install the Git pre-commit hard gate once** (automatically shared across all worktrees via `git rev-parse --git-common-dir`):
106
+
107
+ ```bash
108
+ npx pi-charset install-hook --strict-eol
109
+ ```
110
+
111
+ 3. **Declare agent rules in project `AGENTS.md` / `GEMINI.md`**: Instruct Codex and Antigravity to always use `pi-charset` MCP tools (`charset_read`, `charset_edit`, `charset_apply_patch`, `charset_write`, `charset_grep`, `charset_fix`) for source files and never use shell redirects, `Set-Content`, `iconv`, or `python -c` to rewrite source files.
@@ -0,0 +1,111 @@
1
+ # 多工具协同与同源 MCP(`pi-charset-mcp`)指南
2
+
3
+ [English](../MCP-AND-MULTI-AGENT.md) | 简体中文
4
+
5
+ 当团队需要在 **Pi**、**Codex**、**Antigravity(反重力)** 或 **Claude Code** 之间并行协作开发永久保留 GBK 的老工程(如嵌入式 C/H 固件或传统 Java 项目)时,给不同客户端拼凑第三方编码插件极易因判定规则与换行符策略差异导致互相踩坏文件。
6
+
7
+ `pi-charset` 提供**一套共享内核 + 双形态接入 + 一道 Git 提交硬门禁**,全部读取仓库根目录的同一份 `.pi-charset.json`:
8
+
9
+ 1. **Pi 原生扩展(`src/index.ts`)**:进程内直连内核,零额外协议开销,并带有 `shellGuard` 实时防绕过拦截。
10
+ 2. **同源 Stdio MCP 服务(`pi-charset-mcp`)**:将同一套确定性字节分类、三道写入安全门、SHA-1 读基线、Windows 原子临时文件重试、四种编辑模式、多文件 `apply_patch`、多编码 `grep`、受控换行/转码修复与会话撤销暴露给 **Codex**、**Antigravity**、**Claude Code**、**Cursor** —— **零外部 MCP SDK 依赖、无需安装 Pi 即可独立运行**。
11
+ 3. **Git Pre-Commit 编码质检钩子(`pi-charset install-hook`)**:即便某个 Agent 在复杂任务中偶发绕过工具通过 Shell 改了文件,损坏字节、混合 CRLF/LF 或编码漂移也永远无法进入主干分支。
12
+
13
+ ---
14
+
15
+ ## 1. 一键接入(无需任何 `.pi-charset.json` 文件)
16
+
17
+ **仓库里完全不需要放 `.pi-charset.json` 文件。** `pi-charset-mcp` 默认零配置自适应开箱即用(字节判定 + 向上 3 层兄弟文件推断 + 自动继承 `.editorconfig`/`.gitattributes`/`pom.xml`/`CMakeLists.txt` + 多家族 CJK 搜索)。
18
+
19
+ 如果你希望为纯 GBK 老工程锁定默认编码/行尾且**不想在仓库里新建 JSON 文件**,直接通过启动参数(`--encoding GBK --eol CRLF --prefer-legacy --hashlines --auto-commit`)或 `PI_CHARSET_*` 环境变量传入即可。
20
+
21
+ 一键打印安装命令或配置片段:
22
+
23
+ ```bash
24
+ npx pi-charset mcp-config --client codex
25
+ npx pi-charset mcp-config --client codex --encoding GBK --eol CRLF --prefer-legacy
26
+ npx pi-charset mcp-config --client antigravity
27
+ npx pi-charset mcp-config --client claude
28
+ ```
29
+
30
+ ### Codex(一条命令装好,无需手改配置,也无需 `.pi-charset.json`)
31
+
32
+ ```bash
33
+ # 零配置自适应模式
34
+ codex mcp add pi-charset -- npx -y -p pi-charset pi-charset-mcp
35
+
36
+ # 或直接用参数锁定 GBK + CRLF + 极短头文件保护(仓库里依然零 JSON 文件)
37
+ codex mcp add pi-charset -- npx -y -p pi-charset pi-charset-mcp --encoding GBK --eol CRLF --prefer-legacy
38
+ ```
39
+
40
+ ### Antigravity / Cursor / Windsurf
41
+
42
+ ```json
43
+ {
44
+ "mcpServers": {
45
+ "pi-charset": {
46
+ "command": "npx",
47
+ "args": ["-y", "-p", "pi-charset", "pi-charset-mcp"]
48
+ }
49
+ }
50
+ }
51
+ ```
52
+
53
+ ### Claude Code
54
+
55
+ ```bash
56
+ claude mcp add pi-charset -- npx -y -p pi-charset pi-charset-mcp
57
+ ```
58
+
59
+ ---
60
+
61
+ ## 2. 暴露的 7 个同源 MCP 工具
62
+
63
+ 所有工具共享同一个会话级 `ReadScope`(SHA-1 读取基线、有界撤销日志与纳秒级文件缓存):
64
+
65
+ | 工具名 | 能力说明 |
66
+ | --- | --- |
67
+ | `charset_read` | 编码安全读取,支持 `outline` 大纲、`ranges` 多区间切片、`offset`/`limit`、`hashlines` 锚点并记录 SHA-1 基线 |
68
+ | `charset_write` | 经三道写安全门、Windows 原子重试替换、SHA-1 冲突校验与撤销日志安全写盘 |
69
+ | `charset_edit` | 精确编辑,支持 `edits`(搜索替换)、`hashlines`、`patch` 与 `wholeFile`,改后回传新锚点 |
70
+ | `charset_apply_patch` | 多文件全有或全无预检与有序加锁原子补丁(Codex `*** Begin Patch` / Aider / unified diff),支持整批撤销 |
71
+ | `charset_grep` | 多编码 ripgrep(`UTF-8`、`GB18030`、`GBK`、`Big5`、`Shift_JIS`、`EUC-KR`、`EUC-JP`、`UTF-16`),支持 `filesOnly` 与 `hashlines` |
72
+ | `charset_check` | 只读诊断:传 `path` 输出完整规则决策链;不传 `path` 执行工作区体检 |
73
+ | `charset_fix` | 受控维护:`normalize_eol`(统一换行)、`auto_fix_eol`(批量修复混合换行)、`convert`(闸门预检转码)与 `undo`(撤销),彻底避免 AI 动用 PowerShell/Python 绕过 |
74
+
75
+ ---
76
+
77
+ ## 3. 极短 GBK 头文件防 UTF-8 偶发碰撞(`preferSourceOverUtf8`)
78
+
79
+ 对于只含寥寥几个汉字的无 BOM 极短 `.h` 头文件,极少数 GBK 字节序列恰好也满足合法 UTF-8 语法(例如 6 字节 GBK `"涓浗"` 同时是合法 UTF-8 `"中国"`)。在默认策略下 `isUtf8` 优先于 GBK 回环,可能叠加 `protectUtf8: true` 误判为 UTF-8。
80
+
81
+ 在明确锁死 GBK 的老源码目录,建议在 `.pi-charset.json` 中显式开启 `"preferSourceOverUtf8": true`:
82
+
83
+ ```jsonc
84
+ {
85
+ "$schema": "./node_modules/pi-charset/schema/pi-charset.schema.json",
86
+ "sourceEncoding": "GBK",
87
+ "writeEncoding": "GBK",
88
+ "protectUtf8": true,
89
+ "preferSourceOverUtf8": true,
90
+ "transcodeBash": "auto",
91
+ "newFileLineEnding": "CRLF",
92
+ "overrides": [
93
+ { "pattern": "docs/**", "encoding": "UTF-8", "preferSourceOverUtf8": false, "newFileLineEnding": "LF" }
94
+ ]
95
+ }
96
+ ```
97
+
98
+ 开启后:带 UTF-8 BOM 或含非 GBK 合法 UTF-8 序列的文件仍保持识别为 UTF-8,而同时满足 UTF-8 与 GBK 的无 BOM 字节将稳定按 GBK 处理。
99
+
100
+ ---
101
+
102
+ ## 4. 三工具并行协同与 Git 硬门禁
103
+
104
+ 1. **用 `git worktree` 物理隔离多工具并行开发**:让 Pi(如主目录连 Keil 调试)、Codex 与 Antigravity 各自工作在独立 worktree 中,最后通过 Git 合并,避免频繁触发 SHA-1 读取基线冲突浪费 Token。
105
+ 2. **一键安装共享的 Git Pre-Commit 编码质检钩子**(通过 `git rev-parse --git-common-dir` 自动覆盖全部 worktree):
106
+
107
+ ```bash
108
+ npx pi-charset install-hook --strict-eol
109
+ ```
110
+
111
+ 3. **在项目级 `AGENTS.md` / `GEMINI.md` 写明红线**:要求 Codex 与 Antigravity 读写搜索源码一律走 `pi-charset` MCP 工具(`charset_read` / `charset_edit` / `charset_apply_patch` / `charset_write` / `charset_grep` / `charset_fix`),严禁通过 PowerShell `Set-Content`、重定向、`iconv` 或 `python -c` 直接改写源码文件。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-charset",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Encoding-aware read, write, edit, and grep extension for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,8 @@
34
34
  "node": ">=22.19.0"
35
35
  },
36
36
  "bin": {
37
- "pi-charset": "./tools/pi-charset-cli.mjs"
37
+ "pi-charset": "./tools/pi-charset-cli.mjs",
38
+ "pi-charset-mcp": "./tools/pi-charset-mcp.mjs"
38
39
  },
39
40
  "files": [
40
41
  "src",
@@ -53,7 +54,8 @@
53
54
  "examples",
54
55
  "tools/charset-core.mjs",
55
56
  "tools/scan-encoding.mjs",
56
- "tools/pi-charset-cli.mjs"
57
+ "tools/pi-charset-cli.mjs",
58
+ "tools/pi-charset-mcp.mjs"
57
59
  ],
58
60
  "publishConfig": {
59
61
  "access": "public"
@@ -41,6 +41,11 @@
41
41
  "default": true,
42
42
  "description": "Keep valid UTF-8 files as UTF-8 even inside a legacy sourceEncoding workspace."
43
43
  },
44
+ "preferSourceOverUtf8": {
45
+ "type": "boolean",
46
+ "default": false,
47
+ "description": "On BOM-less files whose bytes satisfy both UTF-8 and the declared multi-byte CJK sourceEncoding (e.g. tiny GBK headers), classify as sourceEncoding instead of UTF-8."
48
+ },
44
49
  "autoCandidates": {
45
50
  "type": "array",
46
51
  "items": { "type": "string" },
@@ -103,6 +108,7 @@
103
108
  "unmappable": { "type": "string", "enum": ["error", "escape", "drop-to-gb18030"] },
104
109
  "autoCandidates": { "type": "array", "items": { "type": "string" } },
105
110
  "protectUtf8": { "type": "boolean" },
111
+ "preferSourceOverUtf8": { "type": "boolean" },
106
112
  "verifyWrite": { "type": "boolean" },
107
113
  "newFileLineEnding": { "type": "string", "enum": ["CRLF", "LF"] }
108
114
  }
package/src/config.ts CHANGED
@@ -61,6 +61,8 @@ export interface OverrideRule {
61
61
  unmappable?: UnmappableStrategy;
62
62
  autoCandidates?: string[];
63
63
  protectUtf8?: boolean;
64
+ /** Prefer configured non-UTF-8 CJK encoding over BOM-less UTF-8 when bytes satisfy both (guards short GBK headers). */
65
+ preferSourceOverUtf8?: boolean;
64
66
  verifyWrite?: boolean;
65
67
  newFileLineEnding?: NewFileLineEnding;
66
68
  }
@@ -72,6 +74,8 @@ export interface EncodingConfig {
72
74
  unmappable?: UnmappableStrategy;
73
75
  verifyWrite?: boolean;
74
76
  protectUtf8?: boolean;
77
+ /** Prefer configured non-UTF-8 CJK encoding over BOM-less UTF-8 when bytes satisfy both (guards short GBK headers). */
78
+ preferSourceOverUtf8?: boolean;
75
79
  autoCandidates?: string[];
76
80
  /** Shell output transcoding mode: false (default) | true/"auto" | explicit encoding name. */
77
81
  transcodeBash?: BashTranscodeMode;
@@ -115,6 +119,7 @@ export interface ResolvedConfig {
115
119
  unmappable: UnmappableStrategy;
116
120
  verifyWrite: boolean;
117
121
  protectUtf8: boolean;
122
+ preferSourceOverUtf8?: boolean;
118
123
  autoCandidates: string[];
119
124
  force: boolean;
120
125
  newFileLineEnding: NewFileLineEnding | null;
@@ -136,6 +141,7 @@ interface ConfigDefaults {
136
141
  unmappable: UnmappableStrategy;
137
142
  verifyWrite: boolean;
138
143
  protectUtf8: boolean;
144
+ preferSourceOverUtf8?: boolean;
139
145
  autoCandidates: string[];
140
146
  transcodeBash: BashTranscodeMode;
141
147
  bashFileDump: boolean;
@@ -182,6 +188,70 @@ function setDirCache(key: string, value: CacheEntry | null): void {
182
188
  }
183
189
  }
184
190
 
191
+ export interface RuntimeConfigDefaults {
192
+ sourceEncoding?: string;
193
+ writeEncoding?: string;
194
+ newFileLineEnding?: NewFileLineEnding;
195
+ preferSourceOverUtf8?: boolean;
196
+ protectUtf8?: boolean;
197
+ unmappable?: UnmappableStrategy;
198
+ hashlines?: boolean;
199
+ autoCommit?: boolean;
200
+ locale?: LocaleMode;
201
+ }
202
+
203
+ let runtimeDefaults: RuntimeConfigDefaults | null = null;
204
+
205
+ /**
206
+ * Configure process-level defaults (used by `pi-charset-mcp` CLI flags and `PI_CHARSET_*` env vars)
207
+ * so users can run or pin encoding policies with zero `.pi-charset.json` files on disk.
208
+ */
209
+ export function setRuntimeDefaults(defaults: RuntimeConfigDefaults | null): void {
210
+ if (!defaults || Object.values(defaults).every((v) => v === undefined)) {
211
+ runtimeDefaults = null;
212
+ } else {
213
+ const clean: RuntimeConfigDefaults = {};
214
+ if (defaults.sourceEncoding) clean.sourceEncoding = normalizeEncoding(defaults.sourceEncoding);
215
+ if (defaults.writeEncoding) clean.writeEncoding = normalizeEncoding(defaults.writeEncoding);
216
+ if (defaults.newFileLineEnding === "CRLF" || defaults.newFileLineEnding === "LF") {
217
+ clean.newFileLineEnding = defaults.newFileLineEnding;
218
+ }
219
+ if (typeof defaults.preferSourceOverUtf8 === "boolean") clean.preferSourceOverUtf8 = defaults.preferSourceOverUtf8;
220
+ if (typeof defaults.protectUtf8 === "boolean") clean.protectUtf8 = defaults.protectUtf8;
221
+ if (defaults.unmappable === "error" || defaults.unmappable === "escape" || defaults.unmappable === "drop-to-gb18030") {
222
+ clean.unmappable = defaults.unmappable;
223
+ }
224
+ if (typeof defaults.hashlines === "boolean") clean.hashlines = defaults.hashlines;
225
+ if (typeof defaults.autoCommit === "boolean") clean.autoCommit = defaults.autoCommit;
226
+ if (defaults.locale === "auto" || defaults.locale === "en" || defaults.locale === "zh-CN") {
227
+ clean.locale = defaults.locale;
228
+ }
229
+ runtimeDefaults = Object.keys(clean).length > 0 ? clean : null;
230
+ }
231
+ _configGen++;
232
+ }
233
+
234
+ export function getRuntimeDefaults(): RuntimeConfigDefaults | null {
235
+ return runtimeDefaults;
236
+ }
237
+
238
+ function runtimeFoundConfig(startDir: string): FoundConfig | null {
239
+ if (!runtimeDefaults?.sourceEncoding) return null;
240
+ const config: EncodingConfig = {
241
+ ...DEFAULTS,
242
+ sourceEncoding: runtimeDefaults.sourceEncoding,
243
+ ...(runtimeDefaults.writeEncoding ? { writeEncoding: runtimeDefaults.writeEncoding } : { writeEncoding: runtimeDefaults.sourceEncoding }),
244
+ ...(runtimeDefaults.newFileLineEnding ? { newFileLineEnding: runtimeDefaults.newFileLineEnding } : {}),
245
+ ...(runtimeDefaults.preferSourceOverUtf8 !== undefined ? { preferSourceOverUtf8: runtimeDefaults.preferSourceOverUtf8 } : {}),
246
+ ...(runtimeDefaults.protectUtf8 !== undefined ? { protectUtf8: runtimeDefaults.protectUtf8 } : {}),
247
+ ...(runtimeDefaults.unmappable ? { unmappable: runtimeDefaults.unmappable } : {}),
248
+ ...(runtimeDefaults.hashlines !== undefined ? { hashlines: runtimeDefaults.hashlines } : {}),
249
+ ...(runtimeDefaults.autoCommit !== undefined ? { autoCommit: runtimeDefaults.autoCommit } : {}),
250
+ ...(runtimeDefaults.locale ? { locale: runtimeDefaults.locale } : {}),
251
+ };
252
+ return { config, configDir: path.resolve(startDir), configPath: "(runtime CLI/env flags)", warnings: [] };
253
+ }
254
+
185
255
  export function configGeneration(): number {
186
256
  return _configGen;
187
257
  }
@@ -525,19 +595,23 @@ export function adaptiveVerdictFor(raw: Buffer): Verdict | undefined {
525
595
  }
526
596
 
527
597
  function makeAdaptiveRule(dir: string, encoding: string, newFileLineEnding: NewFileLineEnding | null = null): ResolvedConfig {
598
+ const rd = runtimeDefaults;
528
599
  return {
529
600
  configDir: dir,
530
601
  sourceEncoding: encoding,
531
602
  writeEncoding: encoding,
532
603
  writeIntent: null,
533
604
  readStrategy: "auto",
534
- unmappable: "error",
605
+ unmappable: rd?.unmappable ?? "error",
535
606
  verifyWrite: true,
536
- protectUtf8: true,
607
+ protectUtf8: rd?.protectUtf8 ?? true,
608
+ preferSourceOverUtf8: rd?.preferSourceOverUtf8 ?? false,
537
609
  autoCandidates: [...DEFAULT_AUTO_CANDIDATES],
538
610
  force: false,
539
- autoCommit: false,
540
- newFileLineEnding,
611
+ autoCommit: rd?.autoCommit ?? false,
612
+ hashlines: rd?.hashlines ?? false,
613
+ locale: rd?.locale,
614
+ newFileLineEnding: newFileLineEnding ?? rd?.newFileLineEnding ?? null,
541
615
  matchedPattern: null,
542
616
  warnings: [],
543
617
  adaptive: true,
@@ -638,7 +712,7 @@ export function findNearestConfigSync(startDir: string): FoundConfig | null {
638
712
  return { config: entry.config, configDir: cur, configPath: entry.configPath, warnings };
639
713
  }
640
714
  const parent = path.dirname(cur);
641
- if (parent === cur) return null;
715
+ if (parent === cur) return runtimeFoundConfig(startDir);
642
716
  cur = parent;
643
717
  }
644
718
  }
@@ -774,6 +848,7 @@ function validateConfig(parsed: Record<string, unknown>, where: string): { confi
774
848
  merged.transcodeBash = normalizeBashMode(parsed.transcodeBash, where, warnings);
775
849
  merged.autoCommit = checkBool("autoCommit", parsed.autoCommit, false);
776
850
  merged.hashlines = checkBool("hashlines", parsed.hashlines, false);
851
+ merged.preferSourceOverUtf8 = checkBool("preferSourceOverUtf8", parsed.preferSourceOverUtf8, false);
777
852
  merged.shellGuard = checkEnum("shellGuard", parsed.shellGuard, ["block", "warn", "off"] as const, DEFAULTS.shellGuard);
778
853
  merged.locale = parsed.locale === undefined ? undefined : checkEnum("locale", parsed.locale, ["auto", "en", "zh-CN"] as const, "auto");
779
854
  merged.newFileLineEnding = normalizeNewFileLineEnding(parsed.newFileLineEnding, where, warnings);
@@ -840,7 +915,7 @@ export async function findNearestConfig(startDir: string, fresh = false): Promis
840
915
  return { config: entry.config, configDir: cur, configPath: entry.configPath, warnings };
841
916
  }
842
917
  const parent = path.dirname(cur);
843
- if (parent === cur) return null;
918
+ if (parent === cur) return runtimeFoundConfig(startDir);
844
919
  cur = parent;
845
920
  }
846
921
  }
@@ -916,6 +991,7 @@ export function resolveFileRule(absFilePath: string, found: FoundConfig): Resolv
916
991
  unmappable: rule?.unmappable ?? config.unmappable ?? DEFAULTS.unmappable,
917
992
  verifyWrite: rule?.verifyWrite ?? config.verifyWrite ?? DEFAULTS.verifyWrite,
918
993
  protectUtf8: rule?.protectUtf8 ?? config.protectUtf8 ?? DEFAULTS.protectUtf8,
994
+ preferSourceOverUtf8: rule?.preferSourceOverUtf8 ?? config.preferSourceOverUtf8 ?? false,
919
995
  autoCandidates: rule?.autoCandidates?.length
920
996
  ? (rule.autoCandidates.map((c) => safeNormalize(String(c))).filter(Boolean) as string[])
921
997
  : config.autoCandidates ?? DEFAULTS.autoCandidates,