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
@@ -0,0 +1,54 @@
1
+ # Design review: the encoding-safety approach re-examined
2
+
3
+ English | [简体中文](./zh-CN/DESIGN-REVIEW.md)
4
+
5
+ ---
6
+
7
+ This is a senior-engineer pass over the whole approach, written after the audit and optimization round that followed `d2da356`. It separates what the evidence supports from what I would change with unlimited time, and it names the changes I would not make. Numbers come from the records under `test/perf/results/`.
8
+
9
+ ## 1. What holds up
10
+
11
+ - **Deterministic in-process classification with an exact round-trip as the safety primitive.** Every guarantee the project makes — Gate 1, Gate 3, the edit snapshot, byte-exact untouched regions — rests on one question: "do these bytes decode and re-encode to themselves under encoding X?" That is the right primitive. It is cheap to test, impossible to fake, and it is what the model evaluation showed the native tools lack: 81 silently corrupted files out of 180 native runs, each reported as success.
12
+ - **One plan for preview and execution, bound to a snapshot.** The stale-plan and stale-read cases are boring in the best way: they fail before any write, and the tests prove the bytes did not move.
13
+ - **Byte-level reference tests instead of string assertions.** Every regression in this round was caught by a test that compared buffers: the whole-body deletion cases, the hard-link refusal, the Gate 3 bypass, the sibling-inference rewrite. String comparisons would have hidden all four.
14
+ - **The measured posture on Raw splice.** Profiling showed diff generation, not codec work, dominating at large sizes. Leaving Raw splice unimplemented was the right call and remains so.
15
+
16
+ ## 2. Where the design cost more than it should
17
+
18
+ The audit found one pattern behind most of the waste: **the classifier always computed the exhaustive candidate list, and every consumer paid for it, although only `/charset-init` ever reads the list.** `grep` needed the verdict; `read`, `write` and `edit` needed the narrowest candidate; nobody needed all seven round-trips.
19
+
20
+ That pattern also hid two real bugs. Classifying the same bytes a second time "under the inferred rule" turned an `unknown` verdict into `config/undecidable`, so the UNKNOWN notice never fired in zero-config mode and `write` was allowed to overwrite undecodable bytes as UTF-8. The fix was to reuse the first verdict instead of recomputing under a preference — the bug disappeared with the waste.
21
+
22
+ A third finding mattered more than any cost: **a byte-exact round-trip does not identify an encoding family.** Most Big5, Shift_JIS and EUC-KR text also decodes and re-encodes losslessly as GBK, as different characters, so the fixed candidate order read those files as GBK mojibake and would have written new text into them as GBK — a mixed-encoding file with every gate silent. The fix decides the family from the decoded text (common and frequent Han characters, kana plus common kanji, frequent Hangul) and refuses non-ASCII writes when the evidence is thin. It is a heuristic, and the design now says so instead of presenting a fixed order as determinism.
23
+
24
+ Two more costs had never been measured: the sibling scan ran on every read of an ASCII file and every new-file write (90 ms each time in a legacy directory), and a pure-ASCII hit line in `grep` triggered classification and a file read although ASCII is identical in every supported encoding.
25
+
26
+ | Change | Effect (Windows 11, Node 24.18.0) |
27
+ | --- | --- |
28
+ | Narrowest-first classification, verdict reuse, sibling cache | Read legacy 408 KB file 36 → 8 ms; ASCII read in a legacy directory 89 → 28 ms cold, 93 → 1.9 ms with the directory cache |
29
+ | ASCII-line grep fast path | Identifier search over 60 GBK files 293 → 44 ms cold, which is ripgrep's own scan time |
30
+
31
+ ## 3. What I would change with unlimited time
32
+
33
+ Ranked by expected value, not by ease.
34
+
35
+ 1. **Split the verdict into "identifiable" and "exhaustive".** `exhaustive` is currently an option on a shared cache entry, which works but needs a `limited` flag to stay correct. A dedicated `candidatesFor(bytes)` query used only by `/charset-init`, with the shared cache holding only the narrow-candidate verdict, would remove the flag and the subtlety.
36
+ 2. **Lenient read, strict write.** A GBK file that uses one of the duplicate byte sequences fails the round-trip and is `unknown` today: it cannot be read, searched or edited. Displaying it with the narrowest candidate that decodes without U+FFFD is always correct for the reader, while `write` and `edit` can keep demanding the exact round-trip. Measure how often real corpora hit this before building it; the model evaluation corpus did not.
37
+ 3. **Use ripgrep's `--context` when the pass encoding matches the file.** Context lines would come straight from rg for the common case, and only mismatched-pass hits would need our own decode. The dense-context output format and the limit cutoff make this fiddlier than it looks, which is why it is not done.
38
+ 4. **Window the display diff around the planned ranges.** At 10 MiB the host's Myers diff is the largest phase in every codec. The plan already knows the changed ranges; a diff built from them would be exact and linear. This is host-side behavior shared with the native `edit`, so it is an upstream contribution as much as a local one.
39
+ 5. **A native codec, only if the numbers demand it.** The remaining cold cost is one decode-and-encode per hit file at roughly 100 MB/s in iconv-lite. A prebuilt N-API GB18030/GBK codec would be 10–20× faster and is the only route to another order of magnitude; it must be proven byte-identical to iconv-lite by exhaustive table comparison first, and it adds a per-platform dependency. Current numbers do not justify it.
40
+ 6. **Take synchronous filesystem calls off the event loop.** `classifyFileCached` (stat, read), `findRg` (spawn) and the Windows console probe are synchronous. They are cached and short, but they run inside the host's loop. The grep data handler is synchronous by nature; the rest can be made async at the call sites that already are.
41
+ 7. **Decide the language of tool messages.** Errors are Chinese with English code prefixes, docs are bilingual. I would make machine-facing messages English and keep the guidance in both docs, because a tool error that a non-Chinese contributor cannot read is a support cost. This is a product decision, not a technical one.
42
+ 8. **Shrink the configuration surface.** `readStrategy: "config"`, `protectUtf8`, `drop-to-gb18030` and `force` each guard a tested branch, and the matrix is hard to hold in one head. `protectUtf8: false` is `writeIntent` under another name; `readStrategy: "config"` changes only the display and could be a `read` option instead of a project setting.
43
+ 9. **One invalidation model.** Four caches (classifier, config directory, sibling inference, grep line source) use three different evidences: mtime and size, a config generation counter, and a stat signature. A single "evidence" abstraction with one test suite would make staleness reasoning uniform.
44
+ 10. **Property tests for the classifier and the stream transcoder.** The edit planner has them; the classifier deserves random valid GBK, Big5 and UTF-8 streams checked against an independent decode, and the chunk splitter deserves random split points.
45
+
46
+ ## 4. Borrowing from Aider
47
+
48
+ Aider's reliability model, read from its source at `5dc9490`, is lean in the right way: an edit applies only when its search block matches exactly, every applied change is committed to git, and `/undo` undoes only commits Aider itself made in the session, after checking that the files are not dirty since, that they existed before, and that nothing was pushed. The extension now mirrors that contract without owning the user's git: a session journal records the bytes before every verified write, `/charset-undo` restores them only while the file is unchanged since (so newer work is never clobbered), and the optional `autoCommit` stages and commits only the file the extension wrote, exactly as Aider does with `git commit -- <files>`. What was not borrowed: committing by default (the host owns its own git workflow) and the lint-and-revert loop (out of scope for an encoding extension).
49
+
50
+ ## 5. What I would not change
51
+
52
+ - **Raw byte splicing, more edit modes, multi-file transactions.** The plan's own stop condition — do not expand the abstraction layer once the measured goal is met — still holds, and the measurements still do not call for them.
53
+ - **The exact-match contract.** The model evaluation showed the strict contract costs nothing on UTF-8 files (3–5% fewer tokens than the native fuzzy matcher) and saves 65% overall. Loosening it would give the savings back.
54
+ - **Zero-config as the default.** It is what makes the extension useful without a configuration file, and this round removed its hidden costs instead of trading them for configuration.
@@ -0,0 +1,46 @@
1
+ # Exact edit engine
2
+
3
+ English | [简体中文](./zh-CN/EDIT-ENGINE.md)
4
+
5
+ ## Contract
6
+
7
+ - Each call edits one existing writable regular file. Links, invalid source bytes, a conflicting read encoding, bare CR, and mixed line endings are rejected. If multiple legacy codecs round-trip, the configured preference and candidate order determine the verdict.
8
+ - `edit` supports four encoding-safe modes against the same immutable snapshot and shared preview (provide exactly one per call):
9
+ - **Search/Replace (`edits`)**: literal unique `oldText -> newText` blocks (default Pi contract).
10
+ - **Hashline (`hashlines`)**: content-addressed line edits (`replace` / `delete` / `insert_after` / `insert_before`) anchored by `<line>:<2-hex>` tags from `read(hashlines=true)`, `read(outline=true)`, or `grep(hashlines=true)` (or `"hashlines": true` in `.pi-charset.json`). Accepts `:`/`#`/`L` anchor dialects, safely strips echoed prefixes, returns updated post-edit anchors + line delta so chained edits need zero re-reads, and detects repeated identical no-op edits (`NOOP_LOOP`). Any shifted or altered line fails with `HASH_MISMATCH` reporting deduplicated ±2 context lines and ±25 shift hints so recovery takes one turn.
11
+ - **Apply Patch (`patch`)**: single-file unified diff (`@@ -a,b +c,d @@`), Codex hunk (`@@ [header]` / `*** End of File`), or Aider `<<<<<<< SEARCH / ======= / >>>>>>> REPLACE` blocks (rejects `*** Move to:` explicitly). Multi-file Codex (`*** Begin Patch`, including `*** Hashline File:`), Aider multi-file `SEARCH/REPLACE`, and `diff --git` patches use the dedicated `apply_patch` tool with all-or-nothing pre-flight validation, deadlock-free sorted path locks, TUI diff rendering, atomic batch `autoCommit`, and batch-level `/charset-undo` (reverting an entire multi-file patch in one command while refusing if any file changed since).
12
+ - **Whole File (`wholeFile`)**: full replacement preserving original encoding, BOM, uniform line endings, and `unchanged` no-op detection.
13
+ - Match `oldText` literally against one original snapshot, using the source's uniform line endings. An empty search, a repeated match (including overlapping occurrences), or overlapping replacements reject the entire batch. An empty replacement deletes the match. Replacements cannot refer to text inserted earlier in the batch.
14
+ - There is no fuzzy, indentation, quote, NFKC, or full-width/half-width rewrite. Suggestions are bounded actual source excerpts, never implicit replacements.
15
+ - The original BOM and encoding are preserved; unaffected text is not changed. For uniform LF/CRLF files, replacement line endings adopt that style. Changes to trailing newlines must be explicit. If the file has no newlines, a replacement may introduce one uniform style. Byte-identical changes return `unchanged` without updating mtime.
16
+ - A successful text read records an observed file version for this extension session. Preview and internal I/O do not refresh that observation. A preview reused at execution stays bound to its original bytes, file identity, and effective configuration. A stale read or plan requires a fresh read and fresh call.
17
+ - Edits and writes serialize by local path within the extension process. The edit verifies encoded output before replacement and reads it back afterward. It checks cancellation before replacement; after replacement starts it reports the actual result. It never automatically replays or rolls back a failed verification.
18
+ - A same-directory temporary file and atomic rename give local-file atomic visibility. The last identity/byte checks reduce but cannot eliminate races with unrelated processes. This is not a multi-file transaction, cross-process CAS, or power-loss durability guarantee. Nonstandard ACLs, streams, and network shares are not qualified.
19
+
20
+ ## Failure and recovery
21
+
22
+ | Code | What to do |
23
+ | --- | --- |
24
+ | `NOT_FOUND`, `AMBIGUOUS_MATCH`, `OVERLAPPING_EDITS`, `INVALID_INPUT` | Re-read and send a unique exact block or independent non-overlapping edits. |
25
+ | `HASH_MISMATCH` | One or more Hashline `<line>:<2-hex>` anchors no longer match the file. Use the actual current `<line>:<hash>\|...` lines reported in the error to retry. |
26
+ | `STALE_READ`, `STALE_PLAN` | Re-read. Review changed content/configuration before making a new call. |
27
+ | `UNENCODABLE`, `UNSUPPORTED_FILE` | Review the source encoding or revise the replacement. Edits that would make a text file classify as binary are rejected before writing. Explicit conversion belongs to `write`. |
28
+ | `AMBIGUOUS_ENCODING` | The bytes round-trip under more than one encoding family and the real one is undecidable. ASCII-only replacements are allowed; for anything else declare `encoding` in `.pi-charset.json`. Nothing was written. |
29
+ | `CANCELLED` | Replacement had not started. |
30
+ | `TEMP_WRITE_FAILED` | The temporary file could not be prepared. No replacement was attempted. Check disk space or write permissions. |
31
+ | `VERIFY_FAILED`, `COMMIT_UNKNOWN` | Re-read the actual file. Do not repeat or roll back blindly. |
32
+
33
+ ## Verify a candidate
34
+
35
+ Run `npm ci` and `npm run verify` using Node 22.19+ or Node 24. Use the pinned Pi host (see lockfile); also smoke-test the Pi version you actually use. A successful Linux run is not evidence that the native Windows locking and local path cases passed. Use a disposable Git checkout and the test fixtures before changing a real legacy workspace.
36
+
37
+ Opt-in end-to-end timing under PowerShell:
38
+
39
+ ```powershell
40
+ $env:CHARSET_BENCH_OUT = "$PWD/edit-bench.json"
41
+ npx vitest run test/perf/edit-engine.bench.test.ts
42
+ ```
43
+
44
+ The fixture generates checked edits for UTF-8, GBK, GB18030 and UTF-16LE at roughly 10 KiB, 100 KiB and 1 MiB, with 1, 5 or 20 replacements. Collect baseline and candidate results on the same machine, filesystem, Node and Pi versions; keep byte validation enabled. The first result per case is reported separately (not a fresh process for each case); the report includes raw warm samples and peak RSS for the test process.
45
+
46
+ `CHARSET_BENCH_SIZES` (KiB) and `CHARSET_BENCH_EDITS` replace the default grid, `CHARSET_BENCH_FILTER` selects cases by `encoding:KiB:edits`, and `CHARSET_PHASES_SIZES` does the same for the stage probe. A 10 MiB size is a stress diagnostic, not a budget target. Search timings have their own opt-in probes: `CHARSET_HITS_TIMINGS` (`test/perf/grep-hits.test.ts`), `CHARSET_GREP_TIMINGS`, `CHARSET_TREE_TIMINGS`, `CHARSET_DENSE_TIMINGS` and `CHARSET_LOOKUP_TIMINGS`. `.github/workflows/bench.yml` runs all of them on hosted Ubuntu and Windows runners on demand and uploads the JSON as artifacts.
@@ -0,0 +1,16 @@
1
+ # Editing engine design and reading guide
2
+
3
+ The [original design, transcribed from the Chinese Word document](zh-CN/EDITING-PLAN.md), was written against pi-charset 0.1.4 at `bed85e5367a7f6d502ac993d46571548e9ce4d63`. It preserves the original estimates, proposals, architecture diagram, test scenarios and pinned sources. Read the [implementation and benchmark record](PROGRESS.md) for measured results.
4
+
5
+ | Task | Contract to preserve |
6
+ | --- | --- |
7
+ | T01 | Freeze the Pi host, edit parameters, failure states and baseline corpus. |
8
+ | T02 | Resolve all exact replacements against one snapshot. Count overlapping occurrences and reject ambiguous edits. |
9
+ | T03 | Use one edit plan for preview and execution. |
10
+ | T04 | Scope observed versions to the session. Preview must not approve a newer file. |
11
+ | T05 | Serialize writes per file, verify identity and bytes before replacement, then read back. Preserve encoding, BOM and line endings. |
12
+ | T06 | Return bounded diagnostics from actual source, including the failed edit index and commit state. |
13
+ | T07 | Check original bytes after rejection and untouched bytes after success. Exercise Windows file sharing and the supported host matrix. |
14
+ | T08 | Compare matched cold and warm workloads, retain raw measurements, verify packaging and maintain both documentation languages. |
15
+
16
+ Sections 5–8 of the original give the matching, concurrency, encoding and error contracts. Sections 10–12 describe the release gates and separate engine timing from model-assisted task outcomes. Appendix A provides interface sketches, B records the historical probes, and C identifies the source revisions. Raw byte splicing, Hashline, unified diff input, automatic indentation recovery and multi-file transactions require separate evidence and design.
@@ -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,92 @@
1
+ # Model-task evaluation: Pi native `edit` versus pi-charset
2
+
3
+ English | [简体中文](./zh-CN/MODEL-EVAL.md)
4
+
5
+ ---
6
+
7
+ ## 1. Question and design
8
+
9
+ The [editing plan](EDITING-PLAN.md) separates engine timing from model-assisted task outcomes (§11.2) and asks for evidence that strict exact editing does not cost more model rounds than the host's native tools. This evaluation runs the same Pi host, model, prompt and tools against the same corpus, changing only whether the pi-charset extension is loaded.
10
+
11
+ | Element | Value |
12
+ | --- | --- |
13
+ | Host | Pi `1.8.0` (`--mode json --print`), tools allowlisted to `read,edit,grep,find`; no bash, no `write`, no MCP, no skills, no context files |
14
+ | Model | Zhipu `glm-5.3-flash`, thinking `low` (follow-ups: thinking `medium`; `glm-5.4`) |
15
+ | Arms | `baseline`: no extension. `charset`: `-e src/index.ts` at `81b4ebd`, zero-config (no `.pi-charset.json`) |
16
+ | Corpus | `github.com/Semi77/2026TI_gimbal` at `b163916` — a National Undergraduate Electronic Design Contest gimbal (two-axis F32C brushless motors, encoders, PID, ADC) with Chinese comments, Keil/CCS on Windows. The same tree naturally mixes 25 GBK files with 35 UTF-8 files and one file of mixed damaged bytes. CRLF throughout. Provenance and encoding census: `test/eval/corpus.json`. The corpus is not redistributed. |
17
+ | Variants | `natural` (bytes as cloned), `utf8` (every GBK file transcoded to UTF-8), `gbk` (every UTF-8 file transcoded to GBK), `natural-config` (natural plus a root `.pi-charset.json` declaring GBK with a narrowed candidate list). The damaged file is left untouched in all of them. |
18
+ | Tasks | 20 single-file edits with deterministic expected bytes: constants, macros, a cast, an operator, arguments, Chinese comments (GBK), a rename across three sites, two occurrences of the same text, disambiguation by neighbouring lines, a Chinese directory path and the damaged file. Reference bytes are produced by byte-level splicing, so untouched regions are the original bytes by construction. Frozen in `test/eval/tasks.json`. |
19
+ | Repetition | 3 runs per task per arm per variant: 6 × 20 × 3 = 360 runs. Each run copies the corpus into a fresh directory and starts a new session. |
20
+ | Outcome | `PASS` (bytes equal reference), `MOJIBAKE_*` (U+FFFD or `EF BF BD` present that was not in the original; `*_ACHIEVED` when the requested text is present), `TIMEOUT` (300 s), `UNCHANGED`, `DRIFT`, `DIVERGED`. `intact` means non-target bytes were preserved. Any change to another `.c`/`.h` file is recorded as collateral. |
21
+
22
+ The prompt names the file, states the change in Chinese, and asks for `read` then `edit` with no other modification. Token figures are provider-reported usage summed over assistant messages: `input`, `cacheRead`, `output`, `reasoning`, `total`.
23
+
24
+ ## 2. Results
25
+
26
+ Per arm, 60 runs each (`test/eval/results/<variant>-<tool>.jsonl`):
27
+
28
+ | Variant / arm | PASS | Intact | Mojibake | Timeout | Turns | Edit errors | Tokens in | cacheRead | out | reasoning | total | Wall p50 | Wall mean |
29
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
30
+ | natural / baseline | 30 | 33 | 24 | 6 | 4.20 | 36 | 6,517 | 16,808 | 3,400 | 3,167 | 26,726 | 4.6 s | 42.8 s |
31
+ | natural / charset | **60** | **60** | 0 | 0 | 3.10 | 3 | 3,282 | 2,747 | 241 | 153 | **6,271** | 4.5 s | **4.7 s** |
32
+ | utf8 / baseline | 57 | 57 | 3 | 0 | 3.07 | 2 | 1,873 | 4,226 | 242 | 153 | 6,341 | 4.2 s | 4.7 s |
33
+ | utf8 / charset | **60** | **60** | 0 | 0 | 3.05 | 1 | 2,126 | 3,834 | 256 | 161 | 6,217 | 4.5 s | 4.8 s |
34
+ | gbk / baseline | 0 | 5 | 54 | 6 | 3.88 | 16 | 4,590 | 12,115 | 2,962 | 2,765 | 19,668 | 4.6 s | 38.0 s |
35
+ | gbk / charset | **60** | **60** | 0 | 0 | 3.07 | 3 | 1,761 | 4,205 | 239 | 156 | **6,206** | 4.6 s | **4.8 s** |
36
+
37
+ Across all 360 runs the native arm passed 87 of 180 and silently corrupted 81 files; pi-charset passed 180 of 180 with no corruption, no timeout and no collateral change. In the native arm the three `utf8`-variant mojibake runs are the damaged file.
38
+
39
+ **Where the native arm fails.** Every edit to a GBK file is wrong: ASCII-only changes (T01, T03, T05, T07, T08) apply at normal cost but replace every Chinese comment in the file with U+FFFD, and the model reports success. Changes that must type Chinese text (T02, T04, T06, T09) cannot match what the model sees: it re-reads, retries and reasons for 47k–164k tokens per run, then either corrupts the file or hits the 300 s limit. Reasoning tokens average 3,167 against 153 — the model thinks twenty times harder about mojibake.
40
+
41
+ **Where the two arms are equal.** On UTF-8 files where both arms pass, pi-charset is not more expensive: natural variant 6,413 vs 6,609 tokens per run (−3.0%), `utf8` variant 6,274 vs 6,515 (−3.7%), with the same number of turns (3.2 vs 3.2, 3.1 vs 3.1). The measured saving therefore comes entirely from avoided rework on non-UTF-8 files.
42
+
43
+ **Medians hide the tail.** On the natural corpus the native arm's median run costs 6,780 tokens against 6,217, and three turns each; its 90th-percentile wall time is 273 s against 5 s. A typical ASCII-only edit of a GBK file (T01, T03, T05, T07, T08) costs the native arm 6,063 tokens and pi-charset 5,724 — the same money, but 0 of 15 native runs preserve the file. The Chinese-comment family (T02, T04, T06, T09) averages 107k tokens and 8.6 turns for the native arm against 5.6k and 3.0 for pi-charset.
44
+
45
+ **The model does not surface the problem.** Of the 81 corrupted native runs, 78 end with the model stating the change is done ("已完成…"). Only 13 of 120 native runs on non-UTF-8 files mention the encoding or garbled text in their final reply, and 7 of those are timeouts.
46
+
47
+ **Diagnostics.** All seven pi-charset edit errors are the two-occurrence task (T16): `[NOT_FOUND; not_applied] Could not exactly locate edits[0] … Actual source lines …`. The model widened `oldText` on the next call and passed every time. The native arm produced 54 edit errors across the same task set.
48
+
49
+ **The damaged file (T10).** `new/SYSTEM/usart/usart.c` is mostly UTF-8 with every `。` truncated to `E3 80 3F` and four GBK lines in the middle. Only GBK round-trips those bytes, so the classifier reports `cjk:GBK` and the model sees mojibake for the UTF-8 portion. The ASCII edit still writes back byte-exactly (3/3 PASS in every variant), while the native arm corrupts it (9/9). pi-charset guarantees byte preservation here, not a correct view; Chinese-text edits on such a file would not match and were not tested.
50
+
51
+ ## 3. Follow-ups: thinking level and a stronger model
52
+
53
+ Two more pairs ran on the natural variant only (60 runs each, `test/eval/results/natural-<tool>-<suffix>.jsonl`):
54
+
55
+ | Natural / arm | PASS | Mojibake | Timeout | Unchanged | Turns | Tokens | Reasoning | Wall mean |
56
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
57
+ | baseline, glm-5.3-flash, low (main) | 30 | 24 | 6 | 0 | 4.20 | 26,726 | 3,167 | 42.8 s |
58
+ | baseline, glm-5.3-flash, medium | 30 | 24 | 6 | 0 | 4.10 | 22,575 | 3,046 | 41.5 s |
59
+ | baseline, glm-5.4, low | 30 | 23 | 4 | 3 | 3.88 | 20,256 | 3,068 | 47.4 s |
60
+ | charset, glm-5.3-flash, low (main) | 60 | 0 | 0 | 0 | 3.10 | 6,271 | 153 | 4.7 s |
61
+ | charset, glm-5.3-flash, medium | 60 | 0 | 0 | 0 | 3.07 | 6,270 | 155 | 4.9 s |
62
+ | charset, glm-5.4, low | 60 | 0 | 0 | 0 | 3.05 | 6,091 | 157 | 6.1 s |
63
+ | baseline, glm-5.3-flash, low, `.pi-charset.json` = GBK | 30 | 24 | 6 | 0 | 4.07 | 23,910 | 3,119 | 41.0 s |
64
+ | charset, glm-5.3-flash, low, `.pi-charset.json` = GBK | 60 | 0 | 0 | 0 | 3.05 | 6,706 | 152 | 4.8 s |
65
+
66
+ Neither more thinking nor a stronger model changes the native outcome: the tool rewrites the bytes whatever the model decides, and the model still reports success. Reasoning tokens in the native arm stay near 3,000 at every setting — the extra thinking is triggered by mojibake, not by the level. glm-5.4 gave up without writing in three runs (counted as unchanged) but was still wrong on all 15 ASCII-only GBK edits. pi-charset's cost is flat across both dimensions (6,091–6,271 tokens, 153–157 reasoning, three turns). A configured deployment (`.pi-charset.json` with `sourceEncoding: "GBK"` and a narrowed candidate list at the corpus root, `natural-config` variant) reproduces the split exactly: 30/60 against 60/60, because existing files are still classified by their bytes and the declared encoding only governs ASCII and new files.
67
+
68
+ ## 4. Interpretation and limits
69
+
70
+ - Zero-config pi-charset is strictly better on this corpus: 100% byte-correct against 48%, 65% fewer tokens overall (77% on the natural corpus), one-sixth of the wall time overall (one-ninth on the natural corpus), and no measurable overhead on UTF-8 files.
71
+ - The native arm's "successes" on GBK files are the dangerous case: the tool and the model both report completion and the file loses its comments.
72
+ - One contest codebase, one model family, Chinese prompts, single-file deterministic edits, three repetitions. Multi-file refactors, compile or test verification and other models are outside this run. Token counts are provider-reported; monetary cost was not computed.
73
+ - Timeouts count as failures; they are the model still working at 300 s, not a tool crash.
74
+
75
+ ## 5. Reproduction
76
+
77
+ The harness lives in `test/eval/` and keeps the corpus and generated files under `%TEMP%\charset-eval` (override with `EVAL_WORK`). It needs a global Pi install with a configured provider; `EVAL_MODEL`, `EVAL_THINKING` and `EVAL_TIMEOUT_MS` override the defaults.
78
+
79
+ ```powershell
80
+ $work = Join-Path $env:TEMP 'charset-eval'
81
+ New-Item -ItemType Directory -Force -Path "$work/cand" | Out-Null
82
+ git clone https://github.com/Semi77/2026TI_gimbal.git "$work/cand/Semi77_2026TI_gimbal"
83
+ git -C "$work/cand/Semi77_2026TI_gimbal" checkout b163916211596d0185bfd7147ed2b39e57b37454
84
+ node test/eval/build-tasks.cjs # validates uniqueness and writes tasks.json
85
+ node test/eval/build-variants.cjs # natural / utf8 / gbk plus per-variant task files
86
+ foreach ($v in 'natural','utf8','gbk') { foreach ($t in 'baseline','charset') {
87
+ node test/eval/run.cjs $v $t --reps 3 --workers 4
88
+ } }
89
+ node test/eval/report.cjs "$work/results"
90
+ ```
91
+
92
+ Raw records for the 360 main runs and 360 follow-up runs are committed under `test/eval/results/`. Each line holds the outcome, hashes, tool counts, edit-error excerpts, per-message usage sums and wall time for one run.