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,311 @@
1
+ # Implementation and benchmark record
2
+
3
+ ## First-principles performance, simplification, and formal invariants · 2026-12-05
4
+
5
+ Driven by four checks — make hot paths dramatically faster, cut dead/duplicated code, turn every fixed bug into a property test, and prove or refute implicit invariants:
6
+
7
+ - **Compiled zero-allocation DBCS round-trip DFA & encodability bitset (`src/encoding/fast-codec.ts`)**: Derived directly from `iconv-lite`'s `DBCSCodec` tables (falling back to `iconv-lite` on multi-codepoint sequences such as Big5-HKSCS combining marks and rare 4-byte non-GB18030 entries like GBK `U+E7C7`). Exhaustively verified against `iconv-lite` on all 231,168 1-byte and high-lead 2-byte sequences across all 7 CJK codecs and all 655,360 BMP code units (`test/invariants.test.ts`). Also replaces eager 12,000-call `COMMON_HAN` import work with a lazy 2-buffer decode (`src/encoding/common-scripts.ts`), switches `detectLineEndingKind` / `planEdits` to SIMD `indexOf`, and eliminates redundant full-file re-encodes/re-decodes in `loadSnapshot`, `prepareEditOutput`, `encodeForWrite`, and `verifyWritten`.
8
+ - **O(changed) windowed edit diff (`src/edit/tool.ts`)**: For files over 16 KiB, `buildWindowedEditDiff` locates line-aligned windows around `plan.ranges` in one zero-copy `indexOf("\n")` scan (O(1) ring-buffer memory) and runs `generateDiffString` + `generateUnifiedPatch` only on the changed windows. Verified byte-for-byte identical against full-file host diff/patch on 200 seeded random multi-edit plans (`test/invariants.test.ts`).
9
+ - **Zero-re-read + ConHost-free Windows `grep` (`src/grep.ts`)**: Uses ripgrep's own decoded line text when `context=0` and the pass matches the file's classified family, passes `--no-config`, removes `windowsHide: true` (matching Pi's built-in grep; on Windows `CREATE_NO_WINDOW` added ~15 ms of ConHost setup to every `rg` child), and fixes the `stop` AbortSignal listener leak.
10
+ - **Counterexamples found & fixed**:
11
+ 1. `incompleteUtf8Tail` (`src/encoding/stream-transcode.ts`) previously accepted invalid UTF-8 lead bytes `0xC0`, `0xC1`, `0xF5..0xFF` and invalid second bytes (`0xE0 0x80`, `0xED 0xA0`), misclassifying GBK streams cut on `0xC0` (`来`/`老`/`类`) as truncated UTF-8; also mid-stream `sampleBytes` cuts inside a multi-byte CJK character turned valid CJK streams into `unknown`. Both fixed and exhaustively proved against RFC 3629.
12
+ 2. `inferFromSiblings` (`src/config.ts`) previously concatenated raw 4 KB prefixes across siblings, losing signal after >4 KB ASCII headers and splicing split multi-byte tails across files; replaced with per-buffer non-ASCII slicing (`decideFamilyFromBuffers`).
13
+ 3. Removed dead `bomBytes` in `src/resolve.ts` and deduplicated config parsing, adaptive rule synthesis, write-plan rejection literals, symlink errors, and binary DataView reads across `src/config.ts`, `src/resolve.ts`, `src/operations.ts`, `src/encoding/classify.ts`, and `src/encoding/mime.ts`.
14
+
15
+ | Measured workload (Windows 11, Node 24.18.0, Pi 1.4.0) | Before | After | Speed-up / Result |
16
+ | --- | ---: | ---: | --- |
17
+ | 10 MiB UTF-8 edit total / `diff` phase (5 edits) | 415 / ~357 ms | **67.6 / 6.7 ms** | **6.1× total / ~53× diff** |
18
+ | 10 MiB GBK edit total / `encode` / `diff` (5 edits, ICU decode + raw splice) | 879 / ~100 / 409 ms | **132.8 / 23.6 / 9.9 ms** | **6.6× total / ~41× diff** |
19
+ | 10 MiB GB18030 edit total / `encode` (4-byte astral on every line, raw splice) | 808 / ~123 ms | **184.2 / 32.4 ms** | **4.4× total / 3.8× encode** |
20
+ | 1 MiB UTF-8 / GBK / GB18030 / UTF-16LE edit total (5 edits) | 45–96 ms | **13.1 / 18.5 / 23.1 / 13.9 ms** | **3.5–5.0× faster** (`encode`: **0.2–1.7 ms**, `diff`: **0.6–0.8 ms**) |
21
+ | 1 MiB GBK `read` / verified `write` (`io-latency`) | 25 / 100 ms | **9–12 / 29–42 ms** | **~2.5× / ~3× faster** |
22
+ | Zero-config read: 408 KB GBK / ASCII w/ 16 GBK siblings (cold) | 8.0 / 28.0 ms | **5.7 / 13.7 ms** | **1.4× / 2.0× faster** |
23
+ | 7 MB GBK file deep hit, context 5 (cold classifier) | 100 ms | **48.5 ms** | **2.1× faster** |
24
+ | `grep` UTF-8 tree: ASCII literal / Chinese + context=1 | 37.9 / 33.6 ms | **17.0 / 17.0 ms** | **Ties native Pi grep (16.7 / 16.7 ms)** |
25
+ | `grep` GBK tree: Chinese literal / Chinese + context=1 | 34.2 / 35.1 ms | **19.7 / 19.2 ms** | **3.2× faster than native (63 / 59.8 ms, 0 hits)** |
26
+
27
+ - **Commercial 4-mode editing & OMP/Aider/Codex ergonomics (`src/edit/hashline.ts`, `src/edit/patch.ts`, `src/edit/apply-patch.ts`, `src/edit/tool.ts`, `src/grep.ts`)**: Unified Search/Replace, Hashline (`read`/`grep` `<line>:<2-hex>|` tags, `#`/`L` dialects, safe echoed-prefix absorption, ±25-line shift-hint `HASH_MISMATCH` recovery with deduplicated surrounding context, `NOOP_LOOP` guard), Apply Patch (Codex `*** Begin Patch` / `*** Begin Patch ***`, Aider single & multi-file `SEARCH/REPLACE` blocks, and Git unified diff with all-or-nothing pre-flight validation and deadlock-free sorted multi-path locking), and Whole File into one immutable `PlannedText` IR. Verified by `test/edit-modes.test.ts` and `test/invariants.test.ts` (393k `fastEncodeDbcs`, 98k ICU `fastDecodeDbcs`, and `spliceEditedBytes` proofs).
28
+ - **Atomic batch `/charset-undo`, unified cache evidence, async hot paths & multi-line `read(outline=true)` (`src/journal.ts`, `src/encoding/file-stamp.ts`, `src/read-view.ts`, `src/config.ts`, `src/grep.ts`, `src/operations.ts`, `src/shell.ts`, `src/index.ts`)**: Grouped all operations of a multi-file `apply_patch` under one `batchId` so `/charset-undo` (or `/charset-undo b<id>`) pre-validates every file under sorted path locks and reverts the entire batch atomically (restoring move sources before deleting destinations, guarding against external edits and out-of-order writes, and evicting expired batches as atomic units under the 32 MiB cap). Unified all four caches (`classify`, `config`, `siblingInference`, `grep` `LineSource`) on `FileStamp` (`dev`/`ino`/`size`/`mtimeMs`/`ctimeMs`) with one shared `invalidatePathCaches` hook across `write`/`edit`/`apply_patch`/`undo`, moved sibling inference, ripgrep discovery, config lookups in `read`/`/charset-status`, and Windows `chcp` detection onto non-blocking async paths, and reused cold-miss `raw` bytes inside `grep` so each cold hit file is read once. Upgraded `read(outline=true)` with multi-line signature lookahead, block-comment/nested-comment/Python-docstring/Markdown-fence immunity, and broad language coverage while keeping linear O(N) runtime and exact `<line>:<2-hex>|` anchors (`test/undo.test.ts`, `test/token-engine.test.ts`, `test/cache-consistency.test.ts`).
29
+
30
+ **Fourth hosted run** ([47495906387](https://github.com/ethan-blue/pi-charset/actions/runs/47495906387) at `277203f`, concurrent passes; `hosted-<os>-bench-round4.json`). Regex over the 2,048-file tree 39 → 16 ms on Ubuntu and 266 → 123 ms on hosted Windows; the limit-one query 10 → 8 ms on Ubuntu and 81 → 123 ms on Windows, where the two stopped passes now cost their spawn and teardown. Identifier search 6.7 / 47 ms, cold 60-file literal search 288 / 318 ms.
31
+
32
+ ## Native tools versus pi-charset, side by side · 2026-12-05
33
+
34
+ `test/perf/grep-native-vs-charset.test.ts` runs Pi's native `grep` and the encoding-aware `grep` on two identical 200-file trees, one UTF-8 and one GBK, with the same four queries; `test/perf/results/windows-native-vs-charset.json` holds every row. Making the encoding passes concurrent is the change measured here: they are independent ripgrep scans, so a query now waits for the slowest pass instead of the sum, and the first pass to fill the limit stops the others.
35
+
36
+ | Query, warm median ms | Tree | Native | Charset, sequential passes | Charset, concurrent passes | Native result | Charset result |
37
+ | --- | --- | ---: | ---: | ---: | --- | --- |
38
+ | ASCII identifier, literal, limit 20 | UTF-8 | 17.6 | 38.2 | 37.9 | 20 hits | 20 hits |
39
+ | Chinese literal, limit 20 | UTF-8 | 15.8 | 31.4 | 31.4 | 20 hits | 20 hits |
40
+ | Han-class regex, limit 20 | UTF-8 | 58.5 | 148.8 | 92.7 | 0 hits | 0 hits |
41
+ | Chinese literal, context 1, limit 5 | UTF-8 | 16.7 | 33.6 | 33.6 | 5 blocks | 5 blocks |
42
+ | ASCII identifier, literal, limit 20 | GBK | 26.7 | 53.0 | 48.8 | 20 hits, **120 U+FFFD** | 20 hits, no U+FFFD |
43
+ | Chinese literal, limit 20 | GBK | 62.0 | 108.9 | 34.2 | **No matches found** | 20 hits |
44
+ | Han-class regex, limit 20 | GBK | 63.5 | 153.1 | 97.5 | 0 hits | 0 hits |
45
+ | Chinese literal, context 1, limit 5 | GBK | 59.2 | 105.9 | 35.1 | **No matches found** | 5 blocks |
46
+
47
+ On a UTF-8 tree both tools return the same lines and the extension costs 15–35 ms more per query for classification and line access, which is below what a person notices. On a GBK tree the native tool is unusable for Chinese, and for ASCII identifiers it returns every Chinese comment as U+FFFD; the extension is correct and, with concurrent passes, faster than the native tool's failed query. The remaining UTF-8-tree gap is the Han-class regex, where the extension always pays for a GB18030 pass that a pure UTF-8 tree never needs: 93 ms against 58 ms on 200 files.
48
+
49
+ ## Reliability round · 2026-12-05
50
+
51
+ Prompted by one standard — a single wrong write is unacceptable — and by Aider's way of making edits safe through git rather than through more machinery ([DESIGN-REVIEW.md](DESIGN-REVIEW.md), section 4).
52
+
53
+ **The write that could go wrong silently.** A probe over the five CJK families showed that the candidate order, not the bytes, was deciding the family: a Big5 file, a Shift_JIS file and an EUC-KR file were all classified GBK in zero-config mode and displayed as mojibake (`琌代刚祘`, `偙傟偼僥僗僩`, `捞巴篮 抛胶飘`), because their bytes also round-trip under GBK. Every gate stayed silent: the untouched bytes are preserved, so only the new text would have been encoded as GBK into a Big5, Japanese or Korean file, mixing encodings. The classifier now scores each round-tripping family by decoding an 8 KB sample from the first non-ASCII byte: common and frequent Han characters for the Chinese families (derived at load time from GB2312 Level 1 and the Big5 common rows, plus hand-written top-frequency lists), kana plus common Japanese kanji for Japanese, and frequency-skewed Hangul for Korean, with minimum evidence counts for the script bonuses. A margin below 0.15 marks the bytes `crossFamilyAmbiguous`: `read` shows the best guess with a warning, and `write`/`edit` refuse non-ASCII content with `AMBIGUOUS_ENCODING`; ASCII replacements stay allowed; a declared `encoding` overrides. Sibling inference uses the same decision, so a Big5 tree writes new files as Big5. Seventeen probe cases, including the same sentence in GBK and Big5, Hong Kong Cantonese in both scripts, three-syllable Korean and GBK containing kana, all resolve correctly (`test/family.test.ts`). Cost: 0.2–0.5 ms per classification for five 8 KB sample decodes, which shows only in the cold classifier search (+30 ms over 60 hit files) and leaves the read path unchanged.
54
+
55
+ **Undo, the Aider way.** Every verified `write` and `edit` records the bytes it replaced in a bounded session journal. `/charset-undo` restores the most recent entry, or the one named by `list`, a sequence number or a path; it removes a file the extension created, and refuses when the file changed or disappeared after the write, mirroring Aider's dirty, missing-in-parent and pushed checks. The restored bytes become the session's observed version so the next edit is not stale. `autoCommit: true` adds Aider's commit step: `git add` the file, `git commit -m … -- <file>`, so other staged work stays staged; a failed commit is a note, never a write failure. Both are covered in `test/undo.test.ts`; the command is registered alongside the other three.
56
+
57
+ ## Audit and optimization round · 2026-12-05
58
+
59
+ A full pass over the source after `d2da356`, driven by five questions: raise performance, remove unused code, find edge cases, re-examine the design, polish. The design-level conclusions are in [DESIGN-REVIEW.md](DESIGN-REVIEW.md); this section records what changed and what the measurements say.
60
+
61
+ **Where the time was going.** The classifier computed the exhaustive seven-candidate list for every consumer, although only `/charset-init` reads it, and the same bytes were classified a second time under the inferred rule. The sibling scan that infers the encoding for ASCII and new files ran uncached on every such read or write. A pure-ASCII hit line in `grep` was classified and read although ASCII is identical in every supported encoding.
62
+
63
+ | Change | Before | After |
64
+ | --- | ---: | ---: |
65
+ | Read legacy GBK file (408 KB), zero-config, cold caches | 36 ms | 8 ms |
66
+ | Read ASCII file in a directory with 16 GBK siblings, cold caches | 89 ms | 28 ms |
67
+ | Same read again, directory cache hit | 93 ms every time | 1.9 ms |
68
+ | Read plus one edit on the legacy file, cold caches | 125 ms | 36 ms |
69
+ | Identifier search, ASCII hit lines in 60 GBK files, cold classifier | 293 ms | 44 ms (ripgrep's own scan) |
70
+
71
+ Mechanism: `classifyBuffer` gained `candidateOrder` and a WeakMap verdict memo; `inferAdaptiveRule` classifies narrowest-first with an early stop and records its verdict for the read and write plans to reuse; `inferFromSiblings` tests one candidate at a time across all legacy siblings, narrowest first, which yields the same common encoding as the exhaustive list, and is cached per directory behind a size-and-mtime signature of the selected siblings. `grep` trusts an ASCII-only line from ripgrep without touching the file. Raw samples: `test/perf/results/windows-read-zero-config.json` and the `round2` block of `windows-grep-hits.json`; reproduce with `CHARSET_READ_TIMINGS` / `CHARSET_HITS_TIMINGS`.
72
+
73
+ **Bugs the audit found.** In zero-config mode the second classification under the rule's UTF-8 preference relabelled undecodable bytes as `config/undecidable`, so (a) the UNKNOWN notice never appeared on read and (b) `write` overwrote them as UTF-8 although Gate 3 promises a refusal. Reusing the first verdict fixes both; `test/zero-config.test.ts` now covers the notice, the edit refusal and the write refusal. Also fixed: the hard-link refusal on `write` is reported before the replacement instead of wrapped in a generic write failure, and a file named `..notes` no longer loses its relative path in grep output.
74
+
75
+ **Behaviour change.** A hit on a pure-ASCII line is now shown even when the file's encoding cannot be determined, because the line is exact regardless; non-ASCII lines in such files stay hidden and `context` falls back to the match line alone. Binary files are unaffected because ripgrep emits no matches for them.
76
+
77
+ **Removed.** `verdictForBuffer` (also lacked the cache's limited-entry rule), `planBomBytes`, `detectLineEnding`, `detectLineEndingFromText`, `buildEncodingGroups`, `globDirPrefix`. `sysnote.ts` now traverses asynchronously instead of blocking the host loop at session start.
78
+
79
+ ## Candidate acceptance · 2026-12-03
80
+
81
+ The baseline is `bed85e5` (v0.1.4). The implementation starts at local commit `202fc73` (v0.1.5-rc.1), and the acceptance fixes are committed as `8f9e98e`.
82
+
83
+ | Task | Evidence |
84
+ | --- | --- |
85
+ | T01 host and contract | Lockfile host and baseline are pinned. The compatibility suite asserts the active Pi version and loads the registered extension. |
86
+ | T02–T03 planning and preview | The shared planner resolves unique non-overlapping ranges in the original snapshot. Preview and execution tests cover stale plans and changing arguments. |
87
+ | T04–T06 observation, commit and diagnostics | Session baselines, identity checks and the atomic replacement path have conflict and fault-injection tests. Added byte-level rejection tests for edits that would classify as binary, and a budget check for JSON-escaped diagnostic excerpts. The edit contract documents recovery codes. |
88
+ | T07 correctness and integration | Windows 11 / Node 24.18.0 passed `npm run verify` on Pi 0.84.0, 1.4.0, 1.7.0 and 1.8.0 (the global install); 354 passing and six skipped per host at `ab27a68`. The native sharing-lock test ran. Skips were two POSIX cases and four opt-in benchmarks. [Hosted CI](https://github.com/ethan-blue/pi-charset/actions/runs/47492178717) on `ab27a68` passed all seven jobs: `ubuntu-latest` with 354 passing and six skipped per job on Node 22 and 24 across Pi 0.84.0, 1.4.0 and 1.7.0, executing the POSIX mode and symlink cases; `windows-latest` with 354 passing and six skipped per job on Node 22 and 24 across Pi 1.4.0 and 1.7.0. Added grep checks for both UTF-16 BOM byte orders and line numbering with bare CR. |
89
+ | T08 performance and packaging | Relative links are checked against the pack list. An actual tarball installed offline in a clean directory exposed all three charset commands through Pi 1.4.0 RPC. Mock GitHub CLI runs exercised the stable and prerelease flags on both create and edit paths. The paired model-task evaluation is recorded in [MODEL-EVAL.md](MODEL-EVAL.md). |
90
+
91
+ The paired model-task evaluation ran 720 headless Pi sessions on a real Chinese contest codebase whose tree mixes GBK and UTF-8 ([MODEL-EVAL.md](MODEL-EVAL.md)): 360 with `glm-5.3-flash` across three corpus variants, and 360 follow-ups on thinking level, `glm-5.4` and a configured `.pi-charset.json`. In the main 360 the native arm passed 87 of 180 runs and silently corrupted 81 files; pi-charset passed 180 of 180 with 65% fewer tokens, no measurable overhead on UTF-8 files, and no collateral change. The follow-ups reproduce the same split at every setting. The owner's own production corpus was not exercised; the contest corpus stands in for it. The candidate has no remote release tag and the owner has decided not to publish it. Raw byte splicing, Hashline, patch input and multi-file transactions remain outside this candidate's scope.
92
+
93
+ ### Repeatable edit timing
94
+
95
+ The same byte-checked benchmark ran against v0.1.4 and the candidate in baseline, candidate, candidate, baseline order on Windows 11 with Node 24.18.0, Pi 1.4.0 and local NTFS fixtures. Each of the 36 cases had 60 warm samples per version and separate first observations with uncontrolled OS cache. Across the first sweep, 35 cases met the historical +20% p95 budget. UTF-16LE at 10 KiB with 20 edits measured 12.15 ms before and 14.61 ms after (+20.28%). A focused repeat with 240 warm samples per version measured 11.00 and 12.19 ms (+10.81%). Keep the checks and record both observations.
96
+
97
+ The repository file `test/perf/results/windows-edit-acceptance.json` preserves all four runs, the focused repeat and 12 candidate phase profiles. At 1 MiB with five edits, diff generation had the largest median phase in all four tested codecs. The phase probe includes snapshot I/O in decode and validation in commit. It does not isolate CPU cost from OS I/O. Use the [benchmark command](EDIT-ENGINE.md#verify-a-candidate) with `CHARSET_BENCH_RUNS=32` for each full run. The focused repeat uses `CHARSET_BENCH_FILTER=^UTF-16LE:10:20$` and `CHARSET_BENCH_RUNS=122`.
98
+
99
+ For the baseline runs, extract `git archive bed85e5` to a scratch directory, use the same installed lockfile dependencies as the candidate, and copy only `test/perf/edit-engine.bench.test.ts` into the baseline. The harness imports each checkout's own registered tool.
100
+
101
+ ### Search per-hit access
102
+
103
+ A search used to decode every file with a hit in full and to classify it with the exhaustive candidate list that only `/charset-init` needs. On Windows 11 with Node 24.18.0, the first search over 60 GBK files of 236 KB took 985 ms, of which ripgrep accounted for 51 ms and classification for about 750 ms (seven candidate round-trips per file). Two changes: hit files are now classified with `exhaustive: false`, which stops at the first lossless candidate, and lines come from a per-file reader that decodes only the requested line range for files over 64 KB, switching to one whole-file decode after 64 requests so dense context output does not regress. `runRgPass` also carries only the partial last line of each chunk instead of re-slicing the accumulated buffer. The unused `buildEncodingGroups` and `globDirPrefix` helpers were removed.
104
+
105
+ | Workload (median ms) | Before `05675c0` | After | Speed-up |
106
+ | --- | ---: | ---: | ---: |
107
+ | 60 files, literal, context 0, cold classifier | 985 | 271 | 3.6× |
108
+ | 60 files, regex, context 3, cold classifier | 885 | 272 | 3.3× |
109
+ | 60 files, literal, context 0, warm classifier | 249 | 104 | 2.4× |
110
+ | 60 files, regex, context 0, warm classifier | 193 | 122 | 1.6× |
111
+ | 7 MB file, one deep hit, context 5 | 146 | 100 | 1.5× |
112
+ | Dense probe: 3 files × 96 hits, limit 289, context 64 | 48.5 | 49.7 | — |
113
+
114
+ The remaining cold cost is one decode-and-encode round-trip per hit file, which is the price of the exact round-trip guarantee that `read` and `edit` rely on. Output is byte-identical: the dense, Chinese-path, bare-CR and UTF-16 BOM regressions are unchanged. Raw samples: `test/perf/results/windows-grep-hits.json`; reproduce with `CHARSET_HITS_TIMINGS=<json path>` and `npx --no-install vitest run test/perf/grep-hits.test.ts`.
115
+
116
+ ### 10 MiB stress diagnostic
117
+
118
+ The plan lists 10 MiB as a diagnostic, not a target. With `CHARSET_BENCH_SIZES=10240` on Windows 11 / Node 24.18.0 / Pi 1.4.0, every cell was byte-exact with zero failures: UTF-8 p50 415 ms (1 edit) and 461 ms (20 edits), GBK 879 / 903 ms, GB18030 808 / 849 ms, UTF-16LE 266 / 284 ms. The phase probe attributes the superlinear growth to the host's `generateDiffString`, which runs a Myers diff over the whole file before pi-charset truncates the display: at 10 MiB it takes 357–409 ms in the legacy codecs against 15–34 ms at 1 MiB, and the native host `edit` pays the same cost. pi-charset's own decode and encode phases grow about 12× per 10× size (`test/perf/results/windows-stress-10mib.json`). Windowing the diff around the planned ranges is the remaining avenue for very large files; it was not needed to meet the 1 MiB budget.
119
+
120
+ ### Write path consistency
121
+
122
+ `atomicReplace` now refuses a destination with more than one hard link, as the edit path already did through `assertEditableFile`. A temp-file rename would have given the written path a fresh inode and silently left the other names on the old content. Both `write` and `edit` reject it with a reason and leave every name intact; `test/regressions.test.ts` covers `write` on both platforms.
123
+
124
+ ### Hosted timing runs
125
+
126
+ `.github/workflows/bench.yml` runs every timing probe on `ubuntu-latest` and `windows-latest` on demand (`workflow_dispatch`, with `os`, `filter` and `runs` inputs). Run 47376712153 on `6c6f1a0` used 4-vCPU runners with Node 24.22.3 and ripgrep 15.1.0 / 16.0.0. The 36-scenario edit benchmark followed the baseline/candidate/candidate/baseline order against `bed85e5` with 32 runs per cell (60 warm samples per side). Runner timing is a cross-check of the local Windows numbers, not a latency guarantee.
127
+
128
+ | 1 MiB p50 ms, before → after | Ubuntu | Hosted Windows |
129
+ | --- | ---: | ---: |
130
+ | UTF-8, 1 / 5 / 20 edits | 53→42, 80→42, 176→45 | 78→64, 100→65, 193→69 |
131
+ | GBK, 1 / 5 / 20 edits | 132→68, 153→70, 260→77 | 166→92, 176→93, 276→97 |
132
+ | GB18030, 1 / 5 / 20 edits | 145→71, 162→72, 271→75 | 174→95, 182→96, 276→98 |
133
+ | UTF-16LE, 1 / 5 / 20 edits | 39→22, 52→23, 108→27 | 61→43, 73→47, 128→47 |
134
+
135
+ Both runners: zero failures on both sides, 34 of 36 cells within the +20% p95 budget, peak RSS equal or lower (Ubuntu 568→540 MiB, Windows 499→473 MiB for the second run of each side). The two cells over budget were 10 KiB operations whose medians improved. A focused retest (run 47379722842, 122 runs per cell, 240 warm samples per side) brought all three Windows cells inside the budget (+8.0%, −38.7%, −25.9%). On Ubuntu the medians stayed equal or better (UTF-8 1.98 vs 2.04 ms, GBK 2.40 vs 2.99, GB18030 2.23 vs 3.14) while two p95 tails remained 1.4 ms and 2.9 ms higher on operations of 2–3 ms; the stage probe shows commit-phase spikes of 40–50 ms landing on both sides of the shared disk, and the candidate issues a few more `lstat`/`fstat` calls per edit for the snapshot and guard. Both runs are kept: `test/perf/results/hosted-<os>-bench.json` and `hosted-<os>-retest.json`.
136
+
137
+ Search probes on the same run. Ubuntu: first search over the 60-file GBK set 207–210 ms against 44–54 ms warm (the cold classification cost is 4–5× on Linux too), deep hit in a 7 MB file 141 ms, dense context 5–25 ms, wrong-pass regex 35 ms first / 17 ms warm, 2,048-file tree literal 14 / 12 ms and regex 35 / 36 ms, repository samples grep 17.5 / 5.7 ms, read 3.6 ms, edit 6.1 ms. Hosted Windows: 262–300 ms cold against 99–140 ms warm, deep hit 170 ms, dense 45–74 ms, tree literal 74 / 73 ms, regex 225 / 218 ms. Linux is the fast regression environment the plan named; the Windows numbers track the local Altior figures within runner noise.
138
+
139
+ **Second hosted run** ([47458909915](https://github.com/ethan-blue/pi-charset/actions/runs/47458909915) at `aa5c30b`, after the audit round; raw samples in `test/perf/results/hosted-<os>-bench-round2.json`). The edit benchmark now shows 0 of 36 cells over the +20% p95 budget on both runners, with zero failures: the verdict reuse in the snapshot removed the extra candidate round-trips that produced the earlier 10 KiB tails. GBK at 1 MiB with 20 edits: 308 → 91 ms on Ubuntu, 344 → 115 ms on hosted Windows. Read probe on Ubuntu: legacy file 12.9 ms cold, ASCII among 16 GBK siblings 28.9 ms cold and 0.75 ms with the directory cache, read plus one edit 52 ms; hosted Windows 14.8 / 38.3 / 1.8 / 60 ms. Identifier search over the 60 GBK files, cold classifier: 11 ms on Ubuntu and 58 ms on Windows, which is ripgrep's scan. The limit-one regex query over the 2,048-file tree runs one rg child: 10 ms on Ubuntu and 81 ms on Windows, against roughly 380–400 ms with three children in the first run.
140
+
141
+ **Third hosted run** ([47492422939](https://github.com/ethan-blue/pi-charset/actions/runs/47492422939) at `ab27a68`, after the reliability round; `hosted-<os>-bench-round3.json`). The family decision adds five 8 KB sample decodes per hit file and nothing to the edit path: GBK at 1 MiB with 20 edits 244 → 74 ms on Ubuntu and 271 → 97 ms on hosted Windows, 0 of 36 cells over budget on Ubuntu and 1 on Windows (`GB18030:100:1` +25%, a cell that was −26% in the focused retest of round 1). Read probe cold 11 ms with the directory cache at 0.3 / 1.4 ms; identifier search 7 ms on Ubuntu and 46 ms on Windows; cold 60-file literal search 246 / 318 ms against 258 / 358 ms in round 2, so the extra decodes are inside runner noise.
142
+
143
+ ## Dense grep handoff · 2026-12-02
144
+
145
+ The registered grep test generates three Chinese-named C files, 96 adjacent matching lines each, CRLF with no final newline, in UTF-8, GBK and GB18030. Six (limit, context) pairs cover (1,1), (95,0), (96,1), (97,2), (289,0), (289,64). It compares the complete tool response and truncation metadata against independently rendered blocks, including overlapping context, paths, order and line numbers. The existing byte-split regression remains in the suite.
146
+
147
+ At context 64, 288 hits expanded to 867,795 UTF-8 bytes and the host returned 51,171 bytes of that text. The formatter now joins at most the 51,200-byte budget plus the first overflowing record, and continues counting the full output for metadata. This bounds the joined text. Peak process memory was not measured.
148
+
149
+ `test/perf/results/windows-dense-search.json` contains two baseline runs (a1/a2) and two modified runs (b1/b2), six sweeps each on Pi 1.4.0. Sample zero is the first sweep in a fresh test process with uncontrolled OS cache. The first high-context observations were 52.51/51.79 ms before and 53.93/52.34 after. For the five warm sweeps, per-run median total time was 47.28/47.98 ms before and 52.29/51.27 after. Child lifetime was 33.71/34.83 → 34.70/34.83 ms, stdout callbacks 9.80/9.58 → 10.27/10.08 ms and post-close work 8.88/9.74 → 10.88/11.13 ms. Child and callback spans overlap. With context zero, modified total was 45.13/43.25 ms and post-close 3.91/4.06 ms. High-context warm runs made five fixture reads over three files. Read time includes I/O; probing and decoding were not separately timed.
150
+
151
+ Run from the repository root to regenerate the fixture and timings:
152
+
153
+ ```powershell
154
+ $env:CHARSET_DENSE_TIMINGS = Join-Path $env:TEMP 'dense-search.json'
155
+ npx --no-install vitest run test/host-integration.test.ts -t "checks dense grep"
156
+ Remove-Item Env:CHARSET_DENSE_TIMINGS
157
+ ```
158
+
159
+ Windows verify passed on Pi 0.84.0, 1.4.0 and 1.7.0 with 318 passed and six skipped per host. The final joined-string size assertion also passed in the working copy. Future performance work should profile byte counting after overflow if representative workloads show a latency issue, retaining exact metadata. Production samples and paid model comparisons remain pending authorization.
160
+
161
+ ## Local handoff · 2026-12-02
162
+
163
+ Start with [the historical design](EDITING-PLAN.md), then read the measured results below. The final 0.1.5-rc.1 working-tree source passed the full Windows gate on Pi 0.84.0, 1.4.0 and 1.7.0 separately. Each host passed type checking, 316 tests (six skipped), and package verification covering 25 Markdown files. The suite checks the installed host version against PI_HOST_VERSION. Timings below were measured on Pi 1.4.0.
164
+
165
+ The registered grep UTF-8 boundary regression feeds real rg JSON stdout to the existing stream decoder one byte at a time, including every byte of the Chinese filename and line text. It requires the exact output `控制.c:2: 控制 NEEDLE`. Run `npx --no-install vitest run test/host-integration.test.ts -t "keeps Chinese grep"`. This test-only follow-up passed on Windows Pi 1.4.0 (317 passed, six skipped); the three-host counts above precede this additional assertion.
166
+
167
+ 1. Run `git status --short --branch` and `git diff --check`. Include any new implementation and test files when copying a working-tree candidate.
168
+ 2. For correctness, run `npm run verify`. To reproduce the host matrix on Altior with its populated npm cache, run the PowerShell block below from the repository root. It installs only inside a fresh local temporary copy.
169
+ 3. For search timings, use the workload-specific commands below. The tests synthesize their own fixtures. Raw millisecond samples for eight runs are in `test/perf/results/windows-search.json`: lookup is the 256-file workload, tree is the 2,048-file lifecycle comparison (a = before, b = after), and content is the paired rg replay. In each series the first element is the first observation.
170
+ 4. Ordinary literal search, filename lookup, verified result limits, child termination and the low-hit multi-pass regex investigation are closed. Reopen only on a reproducible correctness failure or representative high-hit/context-heavy measurements showing substantial extension-side work. Production samples and paid model comparisons remain outstanding.
171
+
172
+ ```powershell
173
+ $root = (Get-Location).Path
174
+ $copy = New-Item -ItemType Directory -Path (Join-Path $env:TEMP ("pi-charset-" + [guid]::NewGuid()))
175
+ git ls-files --cached --others --exclude-standard -- . ':(exclude).alma-snapshots/**' | ForEach-Object {
176
+ if (Test-Path -LiteralPath $_ -PathType Leaf) {
177
+ $target = Join-Path $copy.FullName $_
178
+ [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($target)) | Out-Null
179
+ [IO.File]::Copy((Join-Path $root $_), $target)
180
+ }
181
+ }
182
+ Push-Location $copy.FullName
183
+ $priorHost = $env:PI_HOST_VERSION
184
+ try {
185
+ npm ci --offline --no-audit --no-fund
186
+ if ($LASTEXITCODE) { throw "npm ci failed" }
187
+ foreach ($v in '1.4.0','0.84.0','1.7.0') {
188
+ if ($v -ne '1.4.0') {
189
+ npm install --offline --no-audit --no-fund --no-save --package-lock=false "@earendil-works/pi-ai@$v" "@earendil-works/pi-tui@$v" "@earendil-works/pi-coding-agent@$v"
190
+ if ($LASTEXITCODE) { throw "install failed for $v" }
191
+ }
192
+ $env:PI_HOST_VERSION = $v
193
+ npm run verify
194
+ if ($LASTEXITCODE) { throw "verify failed for $v" }
195
+ }
196
+ } finally {
197
+ $env:PI_HOST_VERSION = $priorHost
198
+ Pop-Location
199
+ }
200
+ ```
201
+
202
+ ## Editing engine
203
+
204
+ Candidate 0.1.5-rc.1 passed local Windows verification with Pi 0.84.0, 1.4.0 and 1.7.0, each with 312 passing and four skipped tests before the grep change. Native sharing-lock and synthetic GBK/CRLF cases passed. Offline Pi 1.7.0 loaded the extension from the working tree. All 36 edit scenarios met the +20% p95 budget in a baseline/candidate/candidate/baseline comparison (60 warm samples per version per scenario). The largest increase was 12.27 to 12.97 ms. Production samples and paid model comparisons remain pending.
205
+
206
+ After the grep change, the working tree passed type checking, 313 tests (four skipped), and the release check covering 25 Markdown files and package contents.
207
+
208
+ ## Search
209
+
210
+ Pi registers `grep` through `createEncodingGrepDefinition`. It discovers ripgrep, applies configured encoding passes, validates each hit against the classified file, and formats context and limits. An unavailable ripgrep or search path delegates to Pi's built-in grep. File-name lookup uses the host's existing tools.
211
+
212
+ The measured change concerns regex hits from a mismatched decoding pass. They are always rejected. Checking regex mode before loading source lines eliminates an entire file read, decode and split on the first such hit per file. Literal verification, file classification and subsequent encoding passes still run as before.
213
+
214
+ | Windows run | First query (ms) | Warm p50 (ms) | Warm p95 (ms) | Warm min–max (ms) |
215
+ | --- | ---: | ---: | ---: | ---: |
216
+ | Before | 425.9 | 364.5 | 378.5 | 351.7–378.5 |
217
+ | After | 116.5 | 81.1 | 96.8 | 76.4–96.8 |
218
+ | After, repeat | 120.0 | 82.1 | 99.6 | 77.9–99.6 |
219
+
220
+ Node 24.18.0, one machine. Each process generated 32 UTF-8 files of 90,000 CRLF filler lines plus one marker, and one GBK file with a real hit. The query deliberately produces wrong-pass hits in UTF-8 files. The first query clears extension caches; OS disk caches are uncontrolled. Each row includes 15 subsequent queries. Nearest-rank p95 is the maximum with this sample size. Timing covers the registered tool's execute method, including rg startup and output formatting. Ordinary single-pass and filename-search workloads were not timed.
221
+
222
+ To reproduce, set `CHARSET_GREP_TIMINGS` to a fresh output JSON path and run `npx --no-install vitest run test/perf/grep-mismatched-pass.test.ts`. Element zero is the first query. Remaining elements are warm timings in milliseconds. Without the variable, the test uses a small fixture and checks exact context, line numbers, the match limit and GBK bytes.
223
+
224
+ <details>
225
+ <summary>Raw query timings (ms)</summary>
226
+
227
+ ```json
228
+ {"before":[425.88,378.46,376.62,358.51,355.17,370.2,363.7,359.76,356.72,369.15,364.53,378.37,351.67,353.49,371.49,365.76],"after":[116.5,79.98,78.58,76.8,76.35,79.04,79.75,81.77,78.98,81.6,96.76,81.06,85.32,88.16,91.26,89.57],"after2":[119.98,80.68,99.58,78.74,80.4,82.14,77.87,80.14,80.26,82.44,82.08,84.92,87.99,99.02,87.07,81.64]}
229
+ ```
230
+
231
+ </details>
232
+
233
+ ## Search limits and ordinary lookups
234
+
235
+ In a GBK fixture, the second byte of 丂 (81 40 hex) resembles an ASCII @. Two such lines preceded real @ characters on lines 3 and 4. The old registered grep returned no match at limit 1. The fixed path validates and deduplicates streamed hits before counting them, stops rg at the accepted limit, and retains decoded lines for at most one file at a time. Regression checks cover limits 1 and 2, CRLF context, bytes, and sorted distinct results across GBK, UTF-8 and ASCII. Windows Pi 1.4.0 verification passed with 314 tests and five skipped; the optional timing test also passed separately.
236
+
237
+ On the same Windows host, 256 synthetic CRLF files (half GBK and half UTF-8) contained one ASCII literal hit and one matching filename. Each of two runs issued one first query and 20 warm queries per tool, alternating extension grep and Pi find. The tools returned the expected path and grep line 2 on every call. The OS filesystem cache was uncontrolled. First-call costs include tool discovery as applicable. Warm quantiles use nearest rank.
238
+
239
+ | Tool | First calls (ms) | Warm p50 (ms) | Warm p95 (ms) |
240
+ | --- | --- | --- | --- |
241
+ | Extension grep, literal NEEDLE | 88.4 / 93.9 | 86.6 / 88.0 | 97.1 / 108.8 |
242
+ | Pi find, needle-*.c | 189.4 / 28.1 | 24.6 / 24.0 | 28.6 / 27.3 |
243
+
244
+ ```powershell
245
+ $env:CHARSET_LOOKUP_TIMINGS = Join-Path $env:TEMP "pi-charset-lookup.json"
246
+ npx --no-install vitest run test/host-integration.test.ts -t "measures literal"
247
+ Remove-Item Env:CHARSET_LOOKUP_TIMINGS
248
+ npx --no-install vitest run test/host-integration.test.ts -t "counts only verified"
249
+ ```
250
+
251
+ ## Large directory tree and process completion
252
+
253
+ On Altior (Windows, Node 24.18.0, Pi 1.4.0), 2,048 synthetic CRLF files were split equally between GBK and UTF-8 in 32 modules three directories deep. One extra ignored file matched both queries. Every search returned exactly the visible target; grep also verified line 2. Each of four fresh test processes ran one first and ten warm queries per tool. The OS cache was uncontrolled.
254
+
255
+ Before the fix, both limit-one regression runs returned after signalling rg but before its close event (0 of 1 closed). After the fix, both returned with 1 of 1 closed. The extension ignores remaining stdout after reaching the verified limit and resolves on close. The previous GBK limit regression still passes. Windows verification: 315 passed, six skipped. The opt-in benchmark passed separately.
256
+
257
+ | Warm median in ms | Before, two runs | After, two runs |
258
+ | --- | --- | --- |
259
+ | Extension literal grep | 152.60 / 154.96 | 151.02 / 153.10 |
260
+ | Host filename find | 26.74 / 28.62 | 27.45 / 27.94 |
261
+
262
+ After the fix, first queries took 164.86 / 153.07 ms for grep and 31.64 / 29.09 ms for find. Warm maxima were 171.01 / 177.66 ms and 30.20 / 29.99 ms respectively. The full-tree query has one visible match and uses the default limit; these timings describe ordinary lookup, not the latency of stopping at the limit.
263
+
264
+ Independent post-fix warm median probes (two runs, ms): uncached rg discovery 0.23 / 0.20, rg --version 8.57 / 8.22, rg --files 18.74 / 19.77, read/decode/split of the tiny GBK target 0.97 / 0.89, host find entry to fd spawn event 4.93 / 5.21, fd --version 12.30 / 12.09. Version probes include process startup and exit. Listing includes traversal and capturing paths. These overlapping probes cannot be added or subtracted to attribute the full search. No stable ordinary-query speedup was established.
265
+
266
+ ```powershell
267
+ $env:CHARSET_TREE_TIMINGS = Join-Path $env:TEMP "pi-charset-tree.json"
268
+ npx --no-install vitest run test/perf/search-tree.test.ts
269
+ Remove-Item Env:CHARSET_TREE_TIMINGS
270
+ ```
271
+
272
+ ## Paired content-search timing
273
+
274
+ The large-tree benchmark above now captures argv from each actual registered grep child and immediately replays the same executable and arguments against the same fixture. Two independent Windows processes each issued 11 queries per mode. The table gives the two warm medians in milliseconds after dropping the first pair. Each replay ran to completion. Registration, process observation and raw JSON capture are test-only.
275
+
276
+ | Query | Registered grep | Child spawn event to close, per pass | Direct replay, per pass | Synchronous stdout callbacks |
277
+ | --- | --- | --- | --- | --- |
278
+ | ASCII literal | 153.85 / 155.17 | 148.61 / 149.73 | 139.71 / 140.72 | 2.51 / 2.69 |
279
+ | Regex | 466.91 / 467.47 | 151+144+150 / 151+149+155 | 144+139+139 / 139+141+144 | 0.79 / 0.83 |
280
+ | Regex, limit one | 407.16 / 397.53 | 147+146+99 / 149+149+98 | 141+142+136 / 141+141+139 | 2.05 / 2.39 |
281
+
282
+ ASCII literals used one UTF-8 pass. Configured regex ran UTF-8, BIG5 and GB18030 in that order. Each pass produced one raw candidate; only the last pass matched the GBK file's classified encoding. A limit of one stopped that pass after validation. The ignored target stayed out. (Update 2026-12-05: since the ASCII-line fast path the target line is trusted in the first pass. With sequential passes that made the limit-one query a single rg child at 71 ms; since passes now run concurrently all three start, the first fill stops the other two, and the query takes about 117 ms on the same machine. The default-limit regex over the same tree dropped from 463 to 271 ms.) Callback spans include stream parsing and candidate validation and overlap child lifetime. The isolated tiny-file read/decode/split medians were 0.93 / 0.91 ms; cache-hit classification was not isolated from other callback work. OS caches were uncontrolled and replay always followed the registered query.
283
+
284
+ Most elapsed time was inside rg content scans on this tree. The measurements do not justify another change to the matcher or decoded-file cache. Reopen this investigation if a representative synthetic workload shows callback time dominates, for example with many legitimate matches requiring context. The same PowerShell command above reproduces the new measurements. Windows verification passed 316 tests with six skipped, including checks for invalid rg syntax, expired caller deadline, accepted-hit limits and child close.
285
+
286
+ ## Formatter memory follow-up
287
+
288
+ Windows, Node 24.18.0 and Pi 1.4.0. The probe executes the formatter extracted from the pinned baseline or working copy with decoded synthetic rows and the installed host truncation code. It omits search and decoding. Each size used eight fresh processes in ABBA ABBA order with one pre-measurement GC. The two variants produced identical content and metadata digests. Run from the repository root:
289
+
290
+ ```powershell
291
+ node test/perf/grep-format-memory.mjs
292
+ node --expose-gc test/perf/grep-format-memory.mjs bounded heavy profile
293
+ python -X utf8 test/perf/rg-memory-win.py
294
+ ```
295
+
296
+ Medians below compare original / bounded. Three files with 96 hits each and context 64 took 5.8 / 7.2 ms. Joined bytes were 867,795 / 51,207. Neither exceeded the process's earlier RSS high-water mark at the median. With 384 hits per file and context 128, elapsed time was 71.0 / 66.7 ms, joined bytes 9,089,699 / 51,230, and increases in process RSS high-water mark 67.01 / 30.97 MiB. Heap-used increases sampled at the join were 8.40 / 7.18 MiB and 50.70 / 2.40 MiB respectively. Heap, external and array-buffer values are point samples subject to GC. External allocation changes cannot be attributed to formatting. Separate standalone rg passes reported observed working-set peaks of 7.55–8.04 MiB across both sizes.
297
+
298
+ The CPU sample attributed 129 ticks to anonymous frames and 13 to appendLine, including possible JIT inlining. It cannot isolate the previous end-to-end latency difference. Keep the bounded implementation. Revisit if repeated representative profiles isolate an actionable cost. Windows verify passed 318 tests, six skipped. `test/perf/results/windows-format-memory.json`, `test/perf/results/windows-format-profile.json`, `test/perf/results/windows-rg-memory.json`.
299
+
300
+
301
+ ## Repository sample acceptance
302
+
303
+ The registered tools processed byte copies of three current working files: src/version.ts, src/grep.ts and docs/CONFIG-GUIDE.md. An independent line scan checked exact literal grep output with zero and one context line, including order, duplicate matches and exclusion of a matching .ignore decoy. A Markdown heading matched on line one. Native Pi find returned exactly the two expected TypeScript paths (membership checked without requiring host traversal order). Read matched normalized text. An isolated comment edit produced the expected bytes, repeating the obsolete edit failed without changing bytes, and the reverse edit restored the original. All three source files compared byte-for-byte equal after testing.
304
+
305
+ Altior Windows, Pi 1.4.0, one targeted run in ms: grep 52.73, context grep 34.62, native find 23.88, Markdown grep 27.14, read 6.66, edit 16.20. These sequential observations do not establish a speed comparison. Full verify passed 319 tests, six skipped, including the synthetic mixed-encoding C regressions. Git listed no tracked C files. Production C and model evaluation remain outside this acceptance.
306
+
307
+ ```powershell
308
+ $env:CHARSET_SELF_TIMINGS='1'
309
+ npx --no-install vitest run test/host-integration.test.ts -t 'isolated repository samples'
310
+ Remove-Item Env:CHARSET_SELF_TIMINGS
311
+ ```
package/docs/RELEASING.md CHANGED
@@ -20,7 +20,7 @@ Every release enforces strict synchronization across five artifacts via `npm run
20
20
  4. [`CHANGELOG.md`](../CHANGELOG.md) (`## [<version>] - YYYY-MM-DD`)
21
21
  5. [`CHANGELOG.zh-CN.md`](../CHANGELOG.zh-CN.md) (`## [<version>] - YYYY-MM-DD`)
22
22
 
23
- `npm run check:release` also validates Pi package manifest fields (`keywords` containing `pi-package` and `pi.extensions` entrypoints), relative Markdown links across all documentation files, and the `npm pack --dry-run` tarball file list.
23
+ `npm run check:release` also validates Pi package manifest fields, relative Markdown links in the checkout and npm tarball, and the `npm pack --dry-run` tarball file list.
24
24
 
25
25
  ## Step-by-Step Release Process
26
26
 
@@ -57,4 +57,6 @@ git push origin main --follow-tags
57
57
  Pushing a `v*.*.*` tag triggers `.github/workflows/release.yml`:
58
58
  1. **Cross-Platform Verification (`verify`)**: Runs `npm ci`, `node tools/check-release.mjs --tag vX.Y.Z`, `npm run typecheck`, and `npm test` on Ubuntu and Windows.
59
59
  2. **GitHub Release (`github-release`)**: Extracts the matching section from `CHANGELOG.md`, builds the `.tgz` package via `npm pack`, and publishes a GitHub Release with the tarball attached.
60
- 3. **Optional npm Registry Publish (`npm-publish`)**: Runs `npm publish --provenance --access public` via GitHub OIDC Trusted Publishing when the repository variable `ENABLE_NPM_PUBLISH` is set to `true`.
60
+ 3. **Optional npm Registry Publish (`npm-publish`)**: Publishes with provenance via GitHub OIDC Trusted Publishing when `ENABLE_NPM_PUBLISH` is `true`.
61
+
62
+ Tags with a SemVer prerelease suffix (such as `v0.1.5-rc.1`) are marked as prereleases on GitHub and use the `next` dist-tag on npm. Stable releases use `latest`.
@@ -42,7 +42,22 @@ npm run verify # 依次执行 typecheck + test + check:release
42
42
  | A-21 | 子会话工具继承 | 未覆盖 | 取决于宿主子会话创建方式,已在 [`README.zh-CN.md`](../../README.zh-CN.md) 边界表说明 |
43
43
  | A-22 | 宿主真实加载器加载 `src/index.ts` 与 RPC 模式启动 | PASS | `test/host-integration.test.ts` |
44
44
  | A-23 | 非 UTF-8 文件 `edit` 预览 diff 计算与缓存失效 | PASS | `test/edit-preview.test.ts` |
45
- | A-24 | `npm pack --dry-run` 打包清单与干净目录加载验证 | PASS | `tools/check-release.mjs` |
45
+ | A-24 | npm 包内容、链接及干净目录安装加载验证 | PASS | `tools/check-release.mjs` 与[候选版验收记录](PROGRESS.md) |
46
+ | A-25 | 所有编辑在同一快照中按唯一精确匹配定位;歧义(包括自身重叠的命中)和相交范围在写入前拒绝 | PASS | `test/edit-plan.test.ts`,契约见 [`EDIT-ENGINE.md`](EDIT-ENGINE.md) |
47
+ | A-26 | 预览与执行共用同一计划;预览过期或参数变化时以 `STALE_PLAN` 拒绝 | PASS | `test/edit-preview.test.ts`、`test/edit-transaction.test.ts` |
48
+ | A-27 | 已读版本按会话隔离:模型可见读取后文件被外部修改则报 `STALE_READ`;预览与内部读取不刷新该版本 | PASS | `test/edit-preview.test.ts`、`test/edit-transaction.test.ts` |
49
+ | A-28 | UTF-8 BOM、GBK、GB18030、UTF-16LE/BE 编辑保持编码、BOM、行尾、EOF 及未触及字节;不可编码、会被判成二进制以及整份删空的输出在写入前拒绝且不动字节 | PASS | `test/edit-transaction.test.ts`、`test/roundtrip.test.ts` |
50
+ | A-29 | 替换前复核文件身份与字节,替换后回读;`TEMP_WRITE_FAILED`、`VERIFY_FAILED`、`COMMIT_UNKNOWN` 均带提交状态且从不回滚 | PASS | `test/edit-transaction.test.ts`、`test/edit-win-lock.test.ts` |
51
+ | A-30 | `edit` 与 `write` 均拒绝符号链接、硬链接和只读目标,原始字节不变 | PASS | `test/edit-transaction.test.ts`、`test/regressions.test.ts` |
52
+ | A-31 | 失败诊断取自真实原文,JSON 转义后仍不超过 4 KiB | PASS | `test/edit-plan.test.ts` |
53
+ | A-32 | 在混编码语料上用模型驱动任务对照原生 `edit` 与 pi-charset | PASS | `test/eval/` 脚本与原始记录;结果见 [`MODEL-EVAL.md`](./MODEL-EVAL.md) |
54
+ | A-33 | 零配置下无法判定的字节保持 `unknown`:`read` 给出 UNKNOWN 提示,`edit` 与 `write` 均拒绝 | PASS | `test/zero-config.test.ts` |
55
+ | A-34 | 兄弟推断与穷尽候选列表得到相同的编码与行尾,按目录缓存,兄弟文件变化后重算 | PASS | `test/zero-config.test.ts` |
56
+ | A-35 | 纯 ASCII 命中行无需读取文件即可显示,编码无法判定的文本亦然;绝不暴露二进制文件 | PASS | `test/grep.test.ts` |
57
+ | A-36 | 按解码后的文本区分 CJK 家族:零配置下 Big5、GBK、Shift_JIS、EUC-JP、EUC-KR 文件各按自身编码读取,包括短注释与混有其他文字的文件 | PASS | `test/family.test.ts`、`test/classify.test.ts` |
58
+ | A-37 | 没有文字证据的字节标记 `crossFamilyAmbiguous`:读取时警告,非 ASCII 的 `write`/`edit` 以 `AMBIGUOUS_ENCODING` 拒绝,ASCII 替换允许,声明的 `encoding` 优先 | PASS | `test/family.test.ts` |
59
+ | A-38 | 每次通过验证的写入都记入日志并可用 `/charset-undo` 撤销:恢复写入前的精确字节,删除新建文件,文件其后有变化或被删除时拒绝,并同步已读版本 | PASS | `test/undo.test.ts`,命令注册见 `test/host-integration.test.ts` |
60
+ | A-39 | 启用 `autoCommit` 时只把写入的文件提交到 git,其他已暂存改动保持暂存;提交失败只产生提示,不影响写入 | PASS | `test/undo.test.ts` |
46
61
 
47
62
  ## 2. 测试套件分布
48
63
 
@@ -59,7 +74,10 @@ npm run verify # 依次执行 typecheck + test + check:release
59
74
  | `test/line-endings.test.ts` | `CRLF`、`LF`、`MIXED` 与 `NONE` 行尾识别与还原 |
60
75
  | `test/operations.test.ts` | `read`/`write`/`edit` 工具操作、`newFileLineEnding`、混合换行拦截、SHA-1 基线校验 |
61
76
  | `test/grep.test.ts` | 多趟编码搜索、逐文件判定过滤、上下文按文件编码解码、零配置多编码搜索 |
62
- | `test/edit-preview.test.ts` | 同步预览路由缓存、GB 文件异步 diff 预览、单字节 `force` 路由 |
77
+ | `test/edit-preview.test.ts` | 预览与执行共用计划、过期计划与过期读取拒绝、流式参数只渲染最新一次 |
78
+ | `test/edit-plan.test.ts` | 纯函数精确规划:含重叠命中的唯一性、批量相交、CRLF 映射、原样替换与显式 EOF 修改的区分、有界诊断、100 次乱序批次对照独立拼接 |
79
+ | `test/edit-transaction.test.ts` | 多编码字节级编辑安全、BOM 与 EOF 保持、整份删空、链接与只读目标、会话快照、取消与提交故障注入 |
80
+ | `test/edit-win-lock.test.ts` | 原生 Windows 共享占用超过重试窗口(仅 Windows) |
63
81
  | `test/shell.test.ts` | 流式 Shell 输出转码、跨块多字节拆分、尾部截断 UTF-8 识别、单文件读取命令识别 |
64
82
  | `test/sysnote.test.ts` | 条件式系统提示注入与 `tool_result` 消息队列 |
65
83
  | `test/zero-config.test.ts` | 零配置自适应读写编辑与同目录邻居编码推断 |
@@ -68,3 +86,13 @@ npm run verify # 依次执行 typecheck + test + check:release
68
86
  | `test/host-integration.test.ts` | 扩展注册、`/charset-status` + `/charset-init` + `/charset-scan` 脚手架命令与 `discoverAndLoadExtensions` 加载器验证 |
69
87
  | `test/perf/io-latency.test.ts` | 300 次 8.7KB GBK 读写循环与 1MB 文件读写延迟 |
70
88
  | `test/perf/grep-scale.test.ts` | 2000 个 GBK/UTF-8 混合文件搜索与 `AbortSignal` 取消延迟 |
89
+ | `test/perf/grep-mismatched-pass.test.ts`、`test/perf/search-tree.test.ts` | 错误编码趟正则命中拒绝并保持 GBK 上下文与行号、子进程收尾、按需计时探针 |
90
+ | `test/perf/grep-hits.test.ts` | 逐命中文件访问:多 GBK 文件分散命中、ASCII 行标识符搜索与大文件深处单命中,冷热分类器;`CHARSET_HITS_TIMINGS` 按需计时
91
+ | `test/perf/read-zero-config.test.ts` | 零配置读取路径:传统编码文件、传统编码兄弟中的 ASCII 文件、目录缓存、读取加编辑;`CHARSET_READ_TIMINGS` 按需计时 |
92
+ | `test/perf/grep-native-vs-charset.test.ts` | 按需在相同的 UTF-8 与 GBK 树上同台运行原生与编码感知 grep(`CHARSET_NATIVE_VS`):延迟、命中数、U+FFFD 与中文显示;只断言本扩展的结果 |
93
+ | `test/edit-modes.test.ts` | 四种编辑模式(Hashline、Search/Replace 与 Aider 块、单/多文件 Codex 与 unified diff Apply Patch、Whole File)、100 组 Hashline 乱序置换不变性、100 组 unified diff 往返一致性、多文件全有或全无预检与无死锁并发 |
94
+ | `test/invariants.test.ts` | 穷举 DFA 往返证明(23.1 万字节序列)、BMP 可编码性证明(65.5 万项)、RFC 3629 尾部截断证明、200 组窗口 diff 逐字节一致测试与历史缺陷属性测试 |
95
+ | `test/family.test.ts` | 五个 CJK 家族的跨家族消歧、歧义拒绝与 ASCII 放行、声明覆盖、兄弟推断按家族、Big5 编辑往返 |
96
+ | `test/undo.test.ts` | 会话撤销日志:写入与编辑后恢复、删除新建文件、拒绝条件、已读版本同步、路径限定自动提交及其失败提示 |
97
+ | `test/perf/edit-engine.bench.test.ts`、`test/perf/edit-engine-phases.bench.test.ts` | 按需启用的 36 场景编辑基准与分阶段计时(`CHARSET_BENCH_OUT`、`CHARSET_PHASES_OUT`);原始样本在 `test/perf/results/` |
98
+ | `test/eval/` | 原生与 pi-charset 成对模型任务对照的脚本、冻结任务集、语料来源与原始记录;用 Node 运行,不属于 vitest |
@@ -10,13 +10,18 @@
10
10
 
11
11
  | 测试环境 | 宿主版本 | 类型检查 | 全量测试 | 扩展加载器 (`discoverAndLoadExtensions`) | CLI 冒烟 (`pi --mode rpc`) |
12
12
  |---|---|---|---|---|---|
13
+ | v0.1.5-rc.1 工作区,Windows 11 / Node 24.18.0 | `0.84.0`、`1.4.0`、`1.7.0` | PASS | 每个宿主 354 项通过、6 项跳过 | PASS | `1.4.0` 安装 tarball 后通过 |
14
+ | v0.1.5-rc.1 候选版,Windows 11 / Node 22.23.4 | `1.4.0` | PASS | 325 项通过、6 项跳过 | PASS | — |
15
+ | v0.1.5-rc.1 工作区,Windows 11 / Node 24.18.0,全局安装 | `1.8.0` | PASS | 354 项通过、6 项跳过 | PASS | PASS(RPC 返回 `charset-status`、`charset-init`、`charset-undo`、`charset-scan`);也是 720 次模型对照的宿主 |
16
+ | v0.1.5-rc.1 `ab27a68`,GitHub Actions `ubuntu-latest` / Node 22、24 | `0.84.0`、`1.4.0`、`1.7.0` | PASS | 每个 job 354 项通过、6 项跳过;POSIX 权限位与符号链接用例已执行 | PASS | — |
17
+ | v0.1.5-rc.1 `ab27a68`,GitHub Actions `windows-latest` / Node 22、24 | `1.4.0`、`1.7.0` | PASS | 每个 job 354 项通过、6 项跳过 | PASS | — |
13
18
  | v0.1.2 锁文件,Windows / Node 24 | `1.4.0` | PASS | 271 项通过,2 项 POSIX 测试跳过 | PASS | — |
14
19
  | v0.1.1 锁文件,Windows / Node 24 | `1.4.0` | PASS | 270 项通过,2 项 POSIX 测试跳过 | PASS | — |
15
20
  | v0.1.0 历史锁文件 | `0.84.3` | PASS | PASS | PASS | — |
16
21
  | 本机宿主环境 (Junction) | `1.2.0` / `1.2.0` / `1.2.0` / `1.2.0` | PASS | PASS | PASS | PASS |
17
22
  | 干净目录打包加载 | `1.4.0` | — | — | PASS | — |
18
23
 
19
- Windows/Linux、Node 22/24 的持续集成验证结果请查看 GitHub Actions。
24
+ `ab27a68` 两行来自 [CI run 47492178717](https://github.com/ethan-blue/pi-charset/actions/runs/47492178717),覆盖 `.github/workflows/ci.yml` 的全部 job;候选版首次托管运行为 `8f9e98e` 的 [47277976527](https://github.com/ethan-blue/pi-charset/actions/runs/47277976527)。按需计时运行见 `.github/workflows/bench.yml`(见进度记录)。两个操作系统的用例数相差一项,原因是 Windows 专属的共享占用用例与 `test/regressions.test.ts` 中两个 POSIX 专属用例互为跳过。
20
25
 
21
26
  根项目中的 `overrides` 用于将本仓库测试环境的 `undici` 更新到已修复版本。扩展安装进其他应用时,npm 不会采用依赖包内的 `overrides`;实际运行 Pi 的环境仍需单独升级和审计。
22
27
 
@@ -4,6 +4,8 @@
4
4
 
5
5
  ---
6
6
 
7
+ **精确编辑:** `edit` 保留检测到的编码和原 BOM,始终执行写后字节校验。显式整文件转码、`unmappable` 后备策略和 `verifyWrite: false` 属于 `write`,不应用于 `edit`。纯 ASCII 文件只有在原字节表示不变时,才会沿用作用域声明或推断出的编码。参见[编辑契约](./EDIT-ENGINE.md)。
8
+
7
9
  ## 1. 快速生成配置与脚手架
8
10
 
9
11
  在 Pi 会话内可直接通过脚手架命令扫描或初始化 `.pi-charset.json`(无需查找扩展包路径,写盘后自动刷新当前会话缓存):
@@ -40,7 +42,7 @@ node tools/scan-encoding.mjs D:/path/to/project --init
40
42
  当工作目录向上查找不到 `.pi-charset.json` 时,扩展默认运行在**零配置自适应模式**:
41
43
  - **已存在文件**:`read`、`write`、`edit` 直接根据文件自身字节判定编码。`GBK`、`GB18030`、`Big5`、`UTF-16` 与 `UTF-8` 文件在读取时自动解码为 UTF-8,在写入时自动保持原文件编码、原行尾(`CRLF` 或 `LF`)与 BOM,并默认启用全部三道写入门禁。
42
44
  - **新建文件与纯 ASCII 文件**:自动扫描同目录下最多 16 个相邻文件(优先匹配同语言后缀族,如 `.c`/`.h`),继承同目录的主流编码与行尾格式(同目录无传统编码文件时默认 `UTF-8`)。
43
- - **多编码搜索(`grep`)**:正则搜索或非 ASCII 字面量搜索执行 `UTF-8 + GB18030` 双趟搜索并按 `file:line` 去重。纯 ASCII 正则也需要分趟,例如 `\p{Han}` 虽然模式只含 ASCII,匹配的却是中文。
45
+ - **多编码搜索(`grep`)**:首趟搜索 UTF-8,并通过 BOM 自动识别 UTF-16。零配置时,正则与非 ASCII 字面量追加 GB18030 搜索趟,再按 `file:line` 去重。纯 ASCII 行上的命中无需分类或读取文件。纯 ASCII 正则也可能命中传统编码文本,例如使用 `\p{Han}` 时。
44
46
  - 仅在需要对新建/纯 ASCII 文件严格固定编码、指定单字节编码(`ISO-8859-1` + `force: true`)、跨编码迁移或开启 `transcodeBash` 时,才需要创建 `.pi-charset.json`。
45
47
 
46
48
  ## 3. 配置字段参考
@@ -57,6 +59,7 @@ node tools/scan-encoding.mjs D:/path/to/project --init
57
59
  | `newFileLineEnding` | 未设置 | 新建文件的行尾格式,可选 `"CRLF"` 或 `"LF"`;不作用于已存在文件 |
58
60
  | `transcodeBash` | `false` | Shell 输出流转码:`false` 关闭;`true` 或 `"auto"` 自动判定并转 UTF-8;或指定具体编码名(如 `"GBK"`)。修改后需重启 Pi |
59
61
  | `bashFileDump` | `true` | 在 `transcodeBash` 开启时生效:`type`、`cat`、`head`、`tail`、`Get-Content` 读取单文件时直接采用该文件的读编码 |
62
+ | `autoCommit` | `false` | 按需启用:通过验证的 `write` 或 `edit` 之后,仅对该文件执行 `git add` 与 `git commit`(Aider 式自动提交)。要求文件位于 git 工作树内;失败只产生提示,不影响写入结果。 |
60
63
  | `overrides` | `[]` | 按路径 glob 覆盖局部规则 |
61
64
 
62
65
  ### 不可映射字符策略选型
@@ -0,0 +1,54 @@
1
+ # 设计复审:重新审视编码安全方案
2
+
3
+ [English](./DESIGN-REVIEW.md) | 简体中文
4
+
5
+ ---
6
+
7
+ 这是在 `d2da356` 之后的审计与优化轮次里,对整个方案做的一次资深工程师视角的复审。它把证据支持的部分与"若有无限时间我会改什么"分开,并点名我不会做的改动。数字来自 `test/perf/results/` 下的记录。
8
+
9
+ ## 一、站得住的部分
10
+
11
+ - **进程内确定性分类,以精确往返作为安全原语。** 项目给出的每一项保证——闸门 1、闸门 3、编辑快照、未触及区域逐字节不变——都归结为同一个问题:"这些字节按编码 X 解码再编码,是否仍是它们自己?"这是正确的原语:检验成本低、无法伪造,也正是模型对照里原生工具所缺的——180 次原生运行静默破坏了 81 个文件,每一次都报告成功。
12
+ - **预览与执行共用一个计划,并绑定快照。** 过期计划与过期读取的失败方式是最理想的那种:在任何写入之前失败,并且测试证明了字节没有动。
13
+ - **字节级参考测试而非字符串断言。** 本轮每一个回归都是被"比较缓冲区"的测试抓住的:整份删空、硬链接拒绝、闸门 3 绕过、兄弟推断重写。字符串比较会把这四个全部漏掉。
14
+ - **对 Raw splice 的实测姿态。** 剖析显示大文件下占主导的是 diff 生成而非编解码。不实现 Raw splice 是正确的,现在依然是。
15
+
16
+ ## 二、设计中代价高于应有的地方
17
+
18
+ 审计发现一个模式掩盖了大部分浪费:**分类器总是在计算穷尽的候选列表,每个消费者都在为它付费,却只有 `/charset-init` 真正读取这个列表。** `grep` 需要的是判定;`read`、`write`、`edit` 需要的是最窄候选;没有人需要全部七次往返。
19
+
20
+ 这个模式还掩盖了两个真实的 bug。"按推断出的规则"对同一批字节再分类一次,会把 `unknown` 变成 `config/undecidable`,于是零配置下 UNKNOWN 提示从不出现,而 `write` 被允许用 UTF-8 覆盖无法解码的字节。修法是复用第一次判定而不是带偏好重算——浪费消失时,bug 也随之消失。
21
+
22
+ 第三个发现比任何成本都重要:**字节级无损往返并不能识别编码家族。** 大多数 Big5、Shift_JIS 和 EUC-KR 文本同样能按 GBK 无损解码再编码,只是变成另外的字,于是固定的候选顺序把这些文件读成 GBK 花码,并会把新文本以 GBK 写进去——一个混合编码的文件,所有门禁都沉默。修法是按解码后的文本判定家族(常用与高频汉字、假名加常用汉字、高频谚文),证据不足时拒绝非 ASCII 写入。这是启发式的,设计现在如实说明,而不再把固定顺序当成确定性。
23
+
24
+ 另有两项成本从未被测量:兄弟文件扫描在每次读取 ASCII 文件和每次新建文件写入时都会执行(传统编码目录里每次 90 ms);`grep` 中纯 ASCII 的命中行会触发分类和文件读取,而 ASCII 在所有受支持编码里都相同。
25
+
26
+ | 改动 | 效果(Windows 11,Node 24.18.0) |
27
+ | --- | --- |
28
+ | 最窄优先分类、判定复用、兄弟目录缓存 | 读取传统编码 408 KB 文件 36 → 8 ms;传统编码目录内读 ASCII 文件 89 → 28 ms(冷),93 → 1.9 ms(目录缓存命中) |
29
+ | grep 的 ASCII 行快速路径 | 60 个 GBK 文件中的标识符搜索 293 → 44 ms(冷),这已经是 ripgrep 自身的扫描时间 |
30
+
31
+ ## 三、若有无限时间我会改什么
32
+
33
+ 按预期价值排序,而非难易。
34
+
35
+ 1. **把判定拆成"可识别"与"穷尽"两种。** `exhaustive` 现在是共享缓存条目上的一个选项,能工作但需要一个 `limited` 标志才能保持正确。改为只供 `/charset-init` 使用的 `candidatesFor(bytes)` 查询,共享缓存只保存最窄候选判定,就可以去掉这个标志及其微妙之处。
36
+ 2. **宽松读取,严格写入。** 使用了重复字节序列的 GBK 文件今天无法往返,被判为 `unknown`:不能读、不能搜、不能编辑。用"解码不产生 U+FFFD 的最窄候选"来显示对读者永远是对的,而 `write` 与 `edit` 可以继续要求精确往返。先测量真实语料里这种情况有多常见再动手;模型对照的语料里没有出现。
37
+ 3. **当搜索趟编码与文件一致时使用 ripgrep 的 `--context`。** 常见情况下下文行直接来自 rg,只有错趟命中才需要我们自己解码。密集上下文的输出格式和上限截断让这件事比看上去复杂,这也是它尚未完成的原因。
38
+ 4. **按计划范围对显示 diff 开窗。** 在 10 MiB 时,宿主的 Myers diff 是每种编码里最大的阶段。计划已经知道变化的范围,据此构造 diff 既精确又线性。这是与原生 `edit` 共享的宿主侧行为,与其说是本地改动,不如说是上游贡献。
39
+ 5. **原生编解码器,仅在数字要求时。** 剩余的冷缓存成本是每个命中文件一次 decode+encode,iconv-lite 大约 100 MB/s。预编译的 N-API GB18030/GBK 编解码器快 10–20 倍,是再提升一个数量级的唯一途径;必须先通过穷尽的表比较证明与 iconv-lite 逐字节一致,而且会增加按平台分发的依赖。现有数字不足以支持它。
40
+ 6. **把同步文件系统调用移出事件循环。** `classifyFileCached`(stat、read)、`findRg`(spawn)和 Windows 控制台探测都是同步的。它们有缓存且很短,但运行在宿主的事件循环里。grep 的数据处理器本质上是同步的;其余的可以在已经是异步的调用点改成异步。
41
+ 7. **决定工具消息的语言。** 错误是中文加英文代码前缀,文档是双语的。我会把面向机器的消息改成英文,把指引保留在两种文档里,因为一个非中文贡献者读不懂的工具错误是支持成本。这是产品决策,不是技术决策。
42
+ 8. **缩小配置面。** `readStrategy: "config"`、`protectUtf8`、`drop-to-gb18030`、`force` 各自守着一个有测试的分支,但整个矩阵很难装进一个脑子。`protectUtf8: false` 就是换了个名字的 `writeIntent`;`readStrategy: "config"` 只改变显示,可以是 `read` 的一个选项而不是项目设置。
43
+ 9. **统一的失效模型。** 四个缓存(分类器、配置目录、兄弟推断、grep 行源)使用三种不同的依据:mtime 与大小、配置代次计数器、stat 签名。一个统一的"依据"抽象配一套测试,可以让过期推理变得一致。
44
+ 10. **为分类器和流式转码器补属性测试。** 编辑计划器已经有了;分类器值得用随机的合法 GBK、Big5、UTF-8 字节流对照独立解码来检验,分块器值得用随机切分点来检验。
45
+
46
+ ## 四、借鉴 Aider
47
+
48
+ 从 Aider `5dc9490` 的源码读到的可靠性模型,精简得恰到好处:编辑只在搜索块精确匹配时才应用;每次应用的改动都提交到 git;`/undo` 只撤销 Aider 本会话自己做的提交,而且先检查文件其后没有未提交改动、在父提交中存在、也没有推送到远端。扩展现在以不接管用户 git 的方式照搬这一契约:会话日志记录每次通过验证的写入之前的字节,`/charset-undo` 只在文件其后未变时恢复(绝不覆盖更新的工作),可选的 `autoCommit` 只暂存并提交扩展自己写的那个文件,与 Aider 的 `git commit -- <files>` 完全一致。没有借的:默认提交(宿主有自己的 git 流程)和 lint-回滚循环(超出编码扩展的范围)。
49
+
50
+ ## 五、我不会改的
51
+
52
+ - **Raw 字节拼接、更多编辑模式、多文件事务。** 计划书自己的停止条件——测得的目标达成后就不再扩建抽象层——仍然成立,测量结果仍然没有要求它们。
53
+ - **精确匹配契约。** 模型对照显示严格契约在 UTF-8 文件上不花代价(比原生模糊匹配少 3–5% token),总体省 65%。放宽它会把节省还回去。
54
+ - **零配置作为默认。** 正是它让扩展无需配置文件就能用,而这一轮做的是移除它的隐性成本,而不是用配置去换。
@@ -0,0 +1,46 @@
1
+ # 精确编辑引擎
2
+
3
+ [English](../EDIT-ENGINE.md) | 简体中文
4
+
5
+ ## 契约
6
+
7
+ - 每次只编辑一个已存在、可写的普通文件。目标为软链接或硬链接、原字节损坏、读取编码与字节判定冲突、含裸 CR 或混合行尾时拒绝编辑。多个传统编码都能无损往返时,按配置偏好与候选顺序判定。
8
+ - `edit` 在同一不可变快照与共享预览之上支持四种编码安全编辑模式(每次调用只传一种):
9
+ - **Search/Replace(`edits`)**:精确唯一匹配 `oldText -> newText`(默认 Pi 契约)。
10
+ - **Hashline(`hashlines`)**:基于内容哈希的行锚定编辑(`replace` / `delete` / `insert_after` / `insert_before`),配合 `read(hashlines=true)`、`read(outline=true)` 或 `grep(hashlines=true)`(或 `.pi-charset.json` 中 `"hashlines": true`)生成的 `<行号>:<2位十六进制>` 标签;兼容 `:`/`#`/`L` 锚点方言、安全剥离回显前缀、修改后自动回传新锚点与行偏移(连续编辑免重读)并内置 `NOOP_LOOP` 防死循环护栏;若目标行发生偏移或改动,立即以 `HASH_MISMATCH` 拒绝并返回去重后的 ±2 行上下文与 ±25 行漂移提示,一轮即可自纠。
11
+ - **Apply Patch(`patch`)**:单文件标准 unified diff(`@@ -a,b +c,d @@`)、Codex 块(`@@ [标题]` / `*** End of File`)或 Aider `<<<<<<< SEARCH / ======= / >>>>>>> REPLACE` 块(单文件模式显式拒绝 `*** Move to:`)。跨多文件的 Codex `*** Begin Patch`(含 `*** Hashline File:`)、Aider 多文件 `SEARCH/REPLACE` 与 `diff --git` 补丁使用独立注册的 `apply_patch` 工具,具备全有或全无预检、有序多路径加锁、TUI 差异渲染、单次原子批量 `autoCommit` 与整批 `/charset-undo` 原子回滚能力。
12
+ - **Whole File(`wholeFile`)**:整文件替换,自动保留原编码、BOM 与统一行尾,内容一致时返回 `unchanged` 不写盘。
13
+ - 所有 `oldText` 在同一原始快照中查找;只兼容源文件统一的 CRLF/LF 表示。空查找文本、重复命中(包括自身相互重叠的命中),或者多项替换范围相交,都会拒绝整批。空替换表示删除。后一项不能匹配前一项新插入的内容。
14
+ - 不自动模糊替换、调整缩进,引号、全角半角或 Unicode 规范形式也不自动变更。失败提示只取少量真实原文,不会自动用提示里的内容替换。
15
+ - 保留原始编码、BOM 和未编辑区域。原有 LF/CRLF 一致时,新文本沿用其行尾。末尾换行只有明确被编辑时才变化;原本没有任何换行的文件允许引入单一行尾样式。原样替换返回 `unchanged`,不写盘、不改时间戳。
16
+ - 本会话成功读取文本后记录已读版本;预览和工具的内部读取不刷新它。执行若复用预览,仍受预览时的字节、文件身份与生效配置约束。出现陈旧版本时先重新读取,再发起新调用。
17
+ - 同一进程内,同一路径的编辑和写入串行执行。替换前检查编码和取消状态,替换后读回核对字节。替换一旦开始,如实报告结果;校验失败后不自动重试或回滚。
18
+ - 同目录临时文件加原子替换用于本地文件。最后的身份和字节复核只能缩小外部进程竞态窗口。这不是跨进程原子比较交换、跨文件事务或断电持久性承诺;特殊 ACL、扩展流和网络盘未验收。
19
+
20
+ ## 失败后怎么做
21
+
22
+ | 结果 | 下一步 |
23
+ | --- | --- |
24
+ | `NOT_FOUND`、`AMBIGUOUS_MATCH`、`OVERLAPPING_EDITS`、`INVALID_INPUT` | 重读,拿唯一的原文或拆成不交叠的替换范围。 |
25
+ | `HASH_MISMATCH` | 一个或多个 Hashline `<行号>:<2位十六进制>` 锚点与当前文件不匹配。根据错误信息中给出的真实 `<行号>:<哈希>\|...` 重新提交。 |
26
+ | `STALE_READ`、`STALE_PLAN` | 查看内容或配置变更后重新发起编辑。 |
27
+ | `UNENCODABLE`、`UNSUPPORTED_FILE` | 检查编码或调整替换内容。如果编辑结果会被判为二进制,写入前即拒绝。显式转码用 `write`。 |
28
+ | `AMBIGUOUS_ENCODING` | 字节可按多个编码家族无损往返,无法确定真实编码。纯 ASCII 替换允许;其他内容需在 `.pi-charset.json` 中声明 `encoding`。未写入任何内容。 |
29
+ | `CANCELLED` | 尚未开始替换。 |
30
+ | `TEMP_WRITE_FAILED` | 临时文件准备失败,未尝试替换目标。检查磁盘空间和写权限。 |
31
+ | `VERIFY_FAILED`、`COMMIT_UNKNOWN` | 重新读取磁盘,不要盲目重试或回滚。 |
32
+
33
+ ## 候选版验收
34
+
35
+ 使用 Node 22.19+ 或 Node 24,执行 `npm ci` 和 `npm run verify`。先覆盖锁文件固定的 Pi,再验证实际使用的宿主版本。Linux 通过不代表 Windows 实际文件占用和路径场景通过。建议先在一次性 Git 副本上试,再使用真实旧工程。
36
+
37
+ 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
+ 语料由测试生成并逐字节检查:UTF-8、GBK、GB18030 和 UTF-16LE,约 10 KiB、100 KiB、1 MiB,以及 1、5、20 次替换。请在同一机器、文件系统、Node 和 Pi 版本下采样,保留字节校验。报告单列每组首次执行(并非每次都重启进程)、原始热路径样本与测试进程峰值 RSS。
45
+
46
+ `CHARSET_BENCH_SIZES`(KiB)与 `CHARSET_BENCH_EDITS` 替换默认网格,`CHARSET_BENCH_FILTER` 按 `encoding:KiB:edits` 选取用例,`CHARSET_PHASES_SIZES` 对分阶段探针做同样的事。10 MiB 属于压力诊断,不是预算目标。搜索计时有各自的按需探针:`CHARSET_HITS_TIMINGS`(`test/perf/grep-hits.test.ts`)、`CHARSET_GREP_TIMINGS`、`CHARSET_TREE_TIMINGS`、`CHARSET_DENSE_TIMINGS` 与 `CHARSET_LOOKUP_TIMINGS`。`.github/workflows/bench.yml` 可按需在托管 Ubuntu 与 Windows runner 上运行全部探针并将 JSON 作为产物上传。