@criogaid/pi-hashline-edit 0.12.0 → 0.13.0

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 (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. package/src/testing/regex-translation-corpus.ts +39 -96
package/LICENSE CHANGED
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
3
  Copyright (c) 2026 Chien Zhang and contributors
4
+ Copyright (c) 2026 Criogaid
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
7
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -4,7 +4,24 @@
4
4
 
5
5
  English · [简体中文](README.zh-CN.md)
6
6
 
7
- Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-agent). The model edits lines by citing anchors from `read` or `grep`; every anchor is checked against the current file before anything is written. Stale or mistaken edits are rejected with enough context for the model to correct them, instead of silently changing the wrong lines.
7
+ Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-agent): line edits cite anchors that are checked against the current file before any write.
8
+
9
+ The model edits lines by citing anchors from `read` or `grep`. Stale or mistaken edits are rejected with enough context for the model to correct them, instead of silently changing the wrong lines.
10
+
11
+ ## Table of Contents
12
+
13
+ - [Why use it](#why-use-it)
14
+ - [Install](#install)
15
+ - [Usage](#usage)
16
+ - [Tools](#tools)
17
+ - [When an edit is rejected](#when-an-edit-is-rejected)
18
+ - [Action Fusion](#action-fusion)
19
+ - [Configuration](#configuration)
20
+ - [Output budgets](#output-budgets)
21
+ - [Limits](#limits)
22
+ - [Development](#development)
23
+ - [Contributing](#contributing)
24
+ - [License](#license)
8
25
 
9
26
  ## Why use it
10
27
 
@@ -24,7 +41,9 @@ pi install npm:@criogaid/pi-hashline-edit
24
41
 
25
42
  Requires Pi 1.5.0 or later. The extension works on local files; for remote or custom storage, set `hashlineEdit.enabled` to `false` and reload Pi to restore the built-in tools.
26
43
 
27
- ## Quick start
44
+ To locate the workspace during registration, the extension runs Windows PowerShell on Windows or `/bin/pwd` on macOS and Linux.
45
+
46
+ ## Usage
28
47
 
29
48
  Pi's model uses the tools automatically. A `read` returns lines with anchors:
30
49
 
@@ -52,25 +71,31 @@ The extension replaces Pi's `read`, `grep`, `edit`, and `write`, and adds `repla
52
71
 
53
72
  | Tool | What it does |
54
73
  | --- | --- |
55
- | `read` | Shows UTF-8 text with anchors, paginated within the model's output budget. Images and files containing NUL bytes go to Pi's built-in read. |
74
+ | `read` | Shows UTF-8 text with anchors, paginated within the model's output budget. For a file the model will not edit, `anchors: false` omits the row prefixes, saving about a third of the tokens. The header stays and standalone CR displays as `␍`. Images and files containing NUL bytes go to Pi's built-in read without a Hashline header. |
56
75
  | `grep` | Searches files and directories with JavaScript regex or literal text; returns anchored matches, file paths, or counts in traversal order; a limit keeps the first matches in that order. Directory searches respect ignore rules and skip `.git` and linked directories, even beneath a directory named in `path`; naming an ignored file or one of those directories itself searches it. |
57
76
  | `edit` | Replaces, inserts, or deletes whole lines by anchor. All operations in one call apply to the same snapshot, or none apply. |
58
77
  | `replace` | Applies literal or regex substitutions across one file. Every rule must match, and overlapping matches reject the batch. |
59
78
  | `write` | Creates a file (`mode: "create"`) or overwrites one (`mode: "overwrite"`), using the content exactly as given. Missing parent directories are created. |
60
79
 
80
+ ### Paths
81
+
61
82
  File paths accept relative or absolute paths, `~`, an optional leading `@`, and `file://` URLs. On Windows, shell drive paths such as `/c/work/file.txt`, `/mnt/c/work/file.txt`, and `/cygdrive/c/work/file.txt` are also accepted. Relative paths resolve from the workspace directory.
62
83
 
63
84
  Path input normalizes several Unicode space characters, including U+202F, to ordinary spaces. To address a filename containing a literal Unicode space, pass a percent-encoded file URL, such as `file:///home/me/space%E2%80%AFname.txt` for a name containing U+202F. Paths returned by `read` and `grep` use a spelling that can be passed back to the tools; keep that spelling, including any URL escapes. The same path syntax applies when `read` delegates images or NUL-containing files to Pi.
64
85
 
65
- Grep visits input paths in the order supplied and uses ripgrep's sorted directory traversal within each root. Repeated candidate paths are searched once, at their first occurrence. This is not global lexicographic sorting of full paths.
86
+ ### grep
66
87
 
67
- Grep matches the LF view with native JavaScript regexes. Without `multiline`, each physical line is searched separately; with it, the whole file is searched and every physical line touched by a match is returned. Context rows do not count toward `limit`. Content output re-reads matched files and omits any whose revision changed; `files` and `count` report the searched snapshot without a second read. Incomplete scans state their diagnostics or scan limit in the report.
88
+ Grep visits input paths in the order supplied and uses ripgrep's sorted directory traversal within each root. Repeated candidate paths are searched once, at their first occurrence. This is not global lexicographic sorting of full paths. A path that does not exist is listed in the report's `missing`, and the other paths are still searched; the call fails with `PATH_NOT_FOUND` when every path is missing or a missing path contains a wildcard.
68
89
 
69
- `replace` matches the same LF view, including a leading BOM. When rebuilding the file, it keeps the original BOM at byte zero, even when a match consumes it or inserts before it. A replacement that consumes the file header and starts with a copied BOM reuses that header; explicitly inserted or internal U+FEFF characters remain content. Use `write` to replace the complete byte representation, including the BOM.
90
+ Grep matches the LF view (the file's text with CRLF line endings shown as LF) with native JavaScript regexes under the `m` flag; `ignoreCase` adds `i`, and grep takes no other flags. Without `multiline`, each physical line is searched separately; with it, the whole file is searched and every physical line touched by a match is returned. Context rows do not count toward `limit`. Content output re-reads matched files and omits any whose revision (the SHA-256 of its bytes) changed; `files` and `count` report the searched snapshot without a second read. Incomplete scans state their diagnostics or scan limit in the report.
70
91
 
71
92
  The grep card preserves file paths and count rows as returned. Only `content` mode formats match rows for display, hiding anchor hashes and folding shared indentation.
72
93
 
73
- An `edit` call puts its small locator first: `path`, `steps`, then optional `then_run`. Each step puts the operation and range before the replacement payload: `action`, `anchor`, optional `end`, then `lines`. This keeps the file and target range visible while arguments stream.
94
+ ### replace
95
+
96
+ `replace` matches the same LF view, including a leading BOM. When rebuilding the file, it keeps the original BOM at byte zero, even when a match consumes it or inserts before it. A replacement that consumes the file header and starts with a copied BOM reuses that header; explicitly inserted or internal U+FEFF characters remain content. Use `write` to replace the complete byte representation, including the BOM.
97
+
98
+ ### edit
74
99
 
75
100
  Edit operations:
76
101
 
@@ -82,13 +107,19 @@ Edit operations:
82
107
 
83
108
  One call takes at most [64 operations](src/pi/edit-tool.ts). Ranges in one call must not overlap, and each gap between lines takes at most one insertion. An insertion at the start of a replaced or deleted range goes before it.
84
109
 
85
- Every tool asks for constrained sampling (Pi's `constrainedSampling`, a strict JSON schema) where the provider supports it, so the model cannot emit fields or values the schema does not declare, or exceed edit's operation limit. Optional fields the call does not use are then written as `null`, including each edit operation's fields that its `action` does not take. For the same reason, grep's `pattern`, `path`, and `glob` take arrays only; on other providers Pi wraps a single string into an array.
110
+ Range operations verify the cited `anchor` and `end`. Interior lines have no individual anchor check. Changes elsewhere before the call do not invalidate unchanged anchors; publication rechecks the bytes read while applying the call and rejects a detected change.
86
111
 
87
- Pi owns argument coercion and acceptance; diagnostics do not change the submitted arguments. Supply operation arrays as declared. Pi drops optional `null` fields before wrapping singleton values into arrays: `replacements: [{ ..., flags: null }]` omits `flags`, while `replacements: { ..., flags: null }` converts it to the string `"null"` and fails flags validation.
112
+ `edit` preserves a leading UTF-8 BOM. A first-line replacement may copy that BOM without duplicating it; U+FEFF in a prepended or inserted line is content.
113
+
114
+ An `edit` call puts its small locator first: `path`, `steps`, then optional `then_run`. Each step puts the operation and range before the replacement payload: `action`, `anchor`, optional `end`, then `lines`. This keeps the file and target range visible while arguments stream.
115
+
116
+ ### Arguments
88
117
 
89
118
  The model sees each tool's full parameter schema; the definitions live in the tool files under [`src/pi/`](src/pi/).
90
119
 
91
- Range operations verify the cited `anchor` and `end`. Interior lines have no individual anchor check. Changes elsewhere before the call do not invalidate unchanged anchors; publication rechecks the bytes read while applying the call and rejects a detected change.
120
+ Every tool asks for constrained sampling (Pi's `constrainedSampling`: the provider restricts the model's output to the tool's strict JSON schema) where the provider supports it, so the model cannot emit fields or values the schema does not declare, or exceed edit's operation limit. Optional fields the call does not use are then written as `null`, including each edit operation's fields that its `action` does not take. For the same reason, grep's `pattern`, `path`, and `glob` take arrays only; on other providers Pi wraps a single string into an array.
121
+
122
+ Pi owns argument coercion and acceptance; diagnostics do not change the submitted arguments. Supply operation arrays as declared. Pi drops optional `null` fields before wrapping singleton values into arrays: `replacements: [{ ..., flags: null }]` omits `flags`, while `replacements: { ..., flags: null }` converts it to the string `"null"` and fails flags validation.
92
123
 
93
124
  ## When an edit is rejected
94
125
 
@@ -110,7 +141,7 @@ Argument mistakes, including a reversed range, are reported per field, with what
110
141
  }
111
142
  ```
112
143
 
113
- The command runs through the session's own Bash tool, so approvals, overrides, and hooks still apply. It starts only if the change succeeded and the file is still as written. A failing command never rolls back the file. The TUI shows the change and the command as separate cards, with a live countdown when a timeout is set.
144
+ The command runs through the session's own Bash tool, so approvals, overrides, and hooks still apply. Fusion checks that the change succeeded and the file is still as written before handing the command to the session. It checks the file again after the command settles; an outside writer can still change it while approval is pending or while the command runs. A failing command never rolls back the file. A Bash override that calls a mutation tool for a target already in the Fusion queue receives an error rather than waiting on that queue. The TUI shows the change and the command as separate cards, with a live countdown when a timeout is set.
114
145
 
115
146
  Command cards use Pi's native tool component for mouse clicks and the global expand shortcut. Each card keeps its own expansion while output streams or the screen redraws. The built-in Bash renderer displays the command's original content and details, which are also saved for session restore; custom Bash renderer overrides are not exposed by the supported Pi API.
116
147
 
@@ -144,24 +175,28 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json`) or a pr
144
175
  | `grep.defaultContext` | `0` | Context lines around each match, 0–20. |
145
176
  | `grep.regexTimeoutMs` / `replace.regexTimeoutMs` | `5000` | Time limit for one regex evaluation, 3000–300000 ms. |
146
177
 
147
- A project's `hashlineEdit` replaces the global one as a whole; invalid values fall back to their defaults. Reload Pi after changing settings. The [configuration schema](src/pi/config.ts) is the source of truth.
178
+ The Pi workspace (the SDK session's `cwd` when embedded) is the base for both `.pi/settings.json` and relative tool paths. A project's `hashlineEdit` replaces the global one as a whole; invalid values fall back to their defaults. Reload Pi after changing settings. `enabled: false` leaves the built-in tools in place; `actionFusion: false` removes `then_run` from new calls but keeps saved command cards visible. The [configuration schema](src/pi/config.ts) is the source of truth.
148
179
 
149
180
  ## Output budgets
150
181
 
151
- The selected model's declared context capacity sets the output budgets; remaining context is never used. For a known capacity, anchored read rows and grep payloads receive one byte per context token, up to 4 MiB. Diagnostic blocks receive a quarter of that budget (at least 512 bytes), and free-text fields a quarter of the block budget (at least 128 bytes). Grep previews keep one UTF-16 code unit per four field bytes. The definitions and fallback values live in [`budgets.ts`](src/pi/budgets.ts).
182
+ The selected model's declared context capacity sets the output budgets; remaining context is never used. A known capacity counts as one byte per context token, up to 4 MiB. Anchored read rows receive a quarter of it and grep payloads an eighth (each at least 512 bytes); a 384,000-token model gets 93.8 KiB per read and 46.9 KiB per grep. Diagnostic blocks receive a quarter of the capacity (at least 512 bytes), and free-text fields a quarter of the block budget (at least 128 bytes). Grep previews keep one UTF-16 code unit per 100 bytes of grep payload and at least 500. A file's first row is narrowed further when it would not otherwise fit the payload after the file's header, and `linePreviewLimit` states the narrowest preview shown. The definitions and fallback values live in [`budgets.ts`](src/pi/budgets.ts).
152
183
 
153
- When model capacity is unknown or invalid, the defaults are 256 KiB for read rows, 50 KiB for grep payloads, 16 KiB per diagnostic block, 4 KiB per free-text field, and 500 UTF-16 code units per grep preview. An explicit `read.maxKiB` overrides only the read cap. Each execution keeps the budget snapshot it started with.
184
+ Argument rejections fit their diagnostic block as serialized JSON. In edit failures, the failure list and the candidate neighborhoods each fit a block in compact JSON, with whole entries or rows omitted and counted. The model-facing `then_run.output` follows the free-text field budget; the command card retains the session Bash result.
185
+
186
+ When model capacity is unknown or invalid, the defaults are 64 KiB for read rows, 50 KiB for grep payloads, 16 KiB per diagnostic block, 4 KiB per free-text field, and 500 UTF-16 code units per grep preview. An explicit `read.maxKiB` overrides only the read cap. Each execution keeps the budget snapshot it started with.
154
187
 
155
188
  Read reports `nextOffset` when its default line limit or byte budget cuts a window; a caller-supplied `limit` alone does not add a `nextOffset` report. A first row that cannot fit gets a `lineTooLong` byte-limit fact. Grep reports payload and preview truncation separately, and plain previews for invalid UTF-8 never carry edit anchors.
156
189
 
157
- For a truncated grep payload, the report says to retry with `context: 0` when the call returned context rows, and otherwise to narrow the search. Inspect full lines before rewriting partial previews: use Bash for paths listed in `invalidUtf8`, and `read` for valid UTF-8.
190
+ For a truncated grep payload, the report says to retry with `context: 0` only when removing context would fit another matching line in the same byte budget; otherwise it suggests narrowing the search. Inspect full lines before rewriting partial previews: use Bash for paths listed in `invalidUtf8`, and `read` for valid UTF-8.
191
+
192
+ If the first grep row has no room for a column range, the preview keeps a complete character with ellipses marking omitted text. When only the ellipsis fits, `linePreviewLimit` is zero.
158
193
 
159
194
  ## Limits
160
195
 
161
196
  - Anchors are short checksums: they catch changed and shifted lines, but can collide and do not prove the model read the line.
162
197
  - Only UTF-8 text is edited; UTF-16 and legacy code pages are not supported.
163
198
  - Revision checks catch most concurrent changes, but there is no cross-process lock or multi-file transaction.
164
- - Overwrites keep symlinks pointing at their target; FIFOs, other non-regular files, and files with multiple hard links are not overwritten.
199
+ - Overwrites keep symlinks pointing at their target. Before publishing, the tool checks that the path still resolves to the same location and that the target is a regular file with only one hard link.
165
200
  - Grep's [search limits](src/pi/grep-search.ts) allow multiline files up to 64 MiB and individual physical lines up to 64 × 1024² UTF-16 code units. Matching runs in at most four workers, each with a 512 MiB V8 old-generation heap limit; individual regex evaluations use the configured timeout.
166
201
  - When discovery falls back to every file in scope, it stops queuing files once their combined sizes reach the [256 MiB whole-scope budget](src/pi/grep-candidates.ts); the last queued file can cross that threshold. The report states when this prevents another file from being scanned. Ripgrep protocol records have a [16 MiB limit](src/pi/rg-process.ts), and its stderr is kept to 64 KiB, beginning and end. Unsupported or over-limit candidate analysis widens discovery; JavaScript still decides the matches.
167
202
 
@@ -177,3 +212,11 @@ For a truncated grep payload, the report says to retry with `context: 0` when th
177
212
  | `npm run test:cartesian` | Slow Cartesian regex matrices; run after changing regex translation or prefiltering. |
178
213
 
179
214
  Result fields and error codes are defined in [`report-schema.ts`](src/pi/report-schema.ts). Module responsibilities are in [`src/core/AGENTS.md`](src/core/AGENTS.md) and [`src/pi/AGENTS.md`](src/pi/AGENTS.md). [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) lists borrowed techniques and test cases.
215
+
216
+ ## Contributing
217
+
218
+ Questions and bug reports go to [GitHub issues](https://github.com/Criogaid/pi-hashline-edit/issues). Pull requests are welcome: run the checks under [Development](#development) first, and follow the commit conventions in [`AGENTS.md`](AGENTS.md).
219
+
220
+ ## License
221
+
222
+ [MIT](LICENSE)
package/README.zh-CN.md CHANGED
@@ -4,7 +4,24 @@
4
4
 
5
5
  [English](README.md) · 简体中文
6
6
 
7
- 为 [Pi](https://github.com/earendil-works/pi-coding-agent) 提供基于行哈希锚点的文件编辑。模型引用 `read` 或 `grep` 输出中的锚点来修改行,写入前每个锚点都会与当前文件核对。过期或错误的修改会被拒绝,并附带足够的信息让模型自行纠正,而不是悄悄改错行。
7
+ 为 [Pi](https://github.com/earendil-works/pi-coding-agent) 提供基于行哈希锚点的文件编辑:修改行时引用锚点,写入前与当前文件核对。
8
+
9
+ 模型引用 `read` 或 `grep` 输出中的锚点来修改行。过期或错误的修改会被拒绝,并附带足够的信息让模型自行纠正,而不是悄悄改错行。
10
+
11
+ ## 目录
12
+
13
+ - [优势](#优势)
14
+ - [安装](#安装)
15
+ - [用法](#用法)
16
+ - [工具](#工具)
17
+ - [修改被拒绝时](#修改被拒绝时)
18
+ - [Action Fusion](#action-fusion)
19
+ - [配置](#配置)
20
+ - [输出预算](#输出预算)
21
+ - [限制](#限制)
22
+ - [开发](#开发)
23
+ - [贡献](#贡献)
24
+ - [许可证](#许可证)
8
25
 
9
26
  ## 优势
10
27
 
@@ -24,7 +41,9 @@ pi install npm:@criogaid/pi-hashline-edit
24
41
 
25
42
  需要 Pi 1.5.0 或更高版本。扩展只处理本地文件;如果使用远程或自定义存储,把 `hashlineEdit.enabled` 设为 `false` 并重新加载 Pi,即可恢复内置工具。
26
43
 
27
- ## 快速上手
44
+ 注册时,扩展通过系统命令定位工作区:Windows 使用 Windows PowerShell,macOS 和 Linux 使用 `/bin/pwd`。
45
+
46
+ ## 用法
28
47
 
29
48
  Pi 的模型会自动使用这些工具。`read` 返回带锚点的行:
30
49
 
@@ -52,25 +71,31 @@ greet.ts · 3 lines
52
71
 
53
72
  | 工具 | 作用 |
54
73
  | --- | --- |
55
- | `read` | 显示带锚点的 UTF-8 文本,按模型的输出预算分页。图片和含 NUL 字节的文件交给 Pi 内置的 read。 |
74
+ | `read` | 显示带锚点的 UTF-8 文本,按模型的输出预算分页。对不打算编辑的文件传 `anchors: false` 时省去行前缀,token 约少三分之一;标题保留,独立的回车符仍显示为 `␍`。图片和含 NUL 字节的文件交给 Pi 内置的 read,不添加 Hashline 标题。 |
56
75
  | `grep` | 用 JavaScript 正则或字面文本搜索文件和目录,按遍历顺序返回带锚点的匹配行、文件路径或计数,设了 limit 时保留该顺序下的前若干条匹配。搜索目录时遵守忽略规则,并跳过 `.git` 和链接目录,在 `path` 指定的目录之下也是如此;在 `path` 中直接指定被忽略的文件或这些目录本身才会搜索。 |
57
76
  | `edit` | 按锚点替换、插入或删除整行。一次调用中的所有操作基于同一份快照,要么全部生效,要么全部不生效。 |
58
77
  | `replace` | 在单个文件内批量执行字面或正则替换。每条规则都必须有匹配,匹配区域重叠时整批拒绝。 |
59
78
  | `write` | 新建文件(`mode: "create"`)或覆盖文件(`mode: "overwrite"`),内容原样写入,缺失的父目录会一并创建。 |
60
79
 
80
+ ### 路径
81
+
61
82
  文件路径支持相对路径、绝对路径、`~`、可选的前导 `@` 和 `file://` URL。Windows 还支持 `/c/work/file.txt`、`/mnt/c/work/file.txt`、`/cygdrive/c/work/file.txt` 等 shell 盘符路径。相对路径以工作区目录为基准解析。
62
83
 
63
84
  路径输入会把 U+202F 等部分 Unicode 空格归一化为普通空格。要精确读取文件名中含有 Unicode 空格的文件,请传入经过百分号编码的文件 URL,例如 `file:///home/me/space%E2%80%AFname.txt` 对应含有 U+202F 的文件名。`read` 和 `grep` 返回的路径可以直接传回工具;请保留返回的写法,包括 URL 转义。`read` 将图片和含 NUL 字节的文件交给 Pi 时,也使用相同的路径语法。
64
85
 
65
- Grep 按传入顺序访问各个搜索路径,在每个根路径内采用 ripgrep 的有序目录遍历。重复候选路径只在第一次出现时搜索。这不是对所有文件完整路径做全局字典序排序。
86
+ ### grep
66
87
 
67
- Grep 用原生 JavaScript 正则匹配 LF 视图。不设 `multiline` 时逐物理行搜索;设为 true 时搜索整个文件,返回匹配涉及的每一物理行。上下文行不计入 `limit`。content 输出会重读匹配文件,略过版本已变的文件;`files` 和 `count` 直接报告搜索时的快照,不做第二次读取。扫描不完整时,报告会给出诊断或扫描上限。
88
+ Grep 按传入顺序访问各个搜索路径,在每个根路径内采用 ripgrep 的有序目录遍历。重复候选路径只在第一次出现时搜索。这不是对所有文件完整路径做全局字典序排序。不存在的路径列在报告的 `missing` 中,其余路径照常搜索;只有全部路径都不存在,或某个不存在的路径含通配符时,调用才以 `PATH_NOT_FOUND` 失败。
68
89
 
69
- `replace` 在相同的 LF 视图上匹配,开头的 BOM 也参与匹配。组装文件时,原 BOM 保持在字节零处,即使匹配包含它或在它前面插入内容。替换包含文件头的匹配时,替换文本开头复制的 BOM 复用原文件头;显式插入或位于正文中的 U+FEFF 字符仍作为内容保留。若需连同 BOM 一起替换完整文件内容,使用 `write`。
90
+ Grep 用带 `m` 标志的原生 JavaScript 正则匹配 LF 视图(把 CRLF 换行显示为 LF 的文件文本);`ignoreCase` 会加上 `i`,grep 不接受其他标志。不设 `multiline` 时逐物理行搜索;设为 true 时搜索整个文件,返回匹配涉及的每一物理行。上下文行不计入 `limit`。content 输出会重读匹配文件,略过版本(文件字节的 SHA-256)已变的文件;`files` 和 `count` 直接报告搜索时的快照,不做第二次读取。扫描不完整时,报告会给出诊断或扫描上限。
70
91
 
71
92
  grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模式会格式化匹配行,隐藏锚点哈希并折叠共有缩进。
72
93
 
73
- `edit` 调用先给出定位信息:`path`、`steps`,再是可选的 `then_run`。每个操作先给出动作和范围,再给出替换内容:`action`、`anchor`、可选的 `end`,最后是 `lines`。参数流式输出时,TUI 可以先显示文件和目标范围。
94
+ ### replace
95
+
96
+ `replace` 在相同的 LF 视图上匹配,开头的 BOM 也参与匹配。组装文件时,原 BOM 保持在字节零处,即使匹配包含它或在它前面插入内容。替换包含文件头的匹配时,替换文本开头复制的 BOM 复用原文件头;显式插入或位于正文中的 U+FEFF 字符仍作为内容保留。若需连同 BOM 一起替换完整文件内容,使用 `write`。
97
+
98
+ ### edit
74
99
 
75
100
  `edit` 的操作:
76
101
 
@@ -82,13 +107,19 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
82
107
 
83
108
  一次调用最多 [64 个操作](src/pi/edit-tool.ts)。一次调用中的范围不能重叠,相邻两行之间的每个位置最多一次插入。位于替换或删除区间起点的插入放在该区间之前。
84
109
 
85
- 在提供方支持时,所有工具都请求约束采样(Pi 的 `constrainedSampling`,即 strict JSON schema),模型因此无法写出 schema 未声明的字段或取值,也无法超出 edit 的操作数上限。这时调用中没用到的可选字段都写 `null`,edit 每个操作里其 `action` 用不到的字段也一样。出于同一原因,grep 的 `pattern`、`path` 和 `glob` 只接受数组;在其他提供方上,Pi 会把单个字符串包成数组。
110
+ 范围操作核对给出的 `anchor`、`end`,不逐行验证区间内部的内容。调用前其他位置的变化不会使未改变的锚点失效;发布前会复核修改操作实际读取的字节,检测到变化时拒绝发布。
86
111
 
87
- 参数转换和接受判定由 Pi 负责;诊断不修改提交的参数。操作数组应按 schema 提交。Pi 先移除可选的 `null` 字段,再把单值包成数组:`replacements: [{ ..., flags: null }]` 会省略 `flags`,而 `replacements: { ..., flags: null }` 会把它转为字符串 `"null"`,随后 flags 校验失败。
112
+ `edit` 保留文件开头的 UTF-8 BOM。替换首行时可以带上原 BOM,不会写入两份;在开头新增或插入的行中,U+FEFF 按正文保留。
113
+
114
+ `edit` 调用先给出定位信息:`path`、`steps`,再是可选的 `then_run`。每个操作先给出动作和范围,再给出替换内容:`action`、`anchor`、可选的 `end`,最后是 `lines`。参数流式输出时,TUI 可以先显示文件和目标范围。
115
+
116
+ ### 参数
88
117
 
89
118
  模型能看到每个工具完整的参数 schema,定义位于 [`src/pi/`](src/pi/) 下的各工具文件。
90
119
 
91
- 范围操作核对给出的 `anchor`、`end`,不逐行验证区间内部的内容。调用前其他位置的变化不会使未改变的锚点失效;发布前会复核修改操作实际读取的字节,检测到变化时拒绝发布。
120
+ 在提供方支持时,所有工具都请求约束采样(Pi 的 `constrainedSampling`:提供方把模型输出限制在工具的 strict JSON schema 内),模型因此无法写出 schema 未声明的字段或取值,也无法超出 edit 的操作数上限。这时调用中没用到的可选字段都写 `null`,edit 每个操作里其 `action` 用不到的字段也一样。出于同一原因,grep 的 `pattern`、`path` 和 `glob` 只接受数组;在其他提供方上,Pi 会把单个字符串包成数组。
121
+
122
+ 参数转换和接受判定由 Pi 负责;诊断不修改提交的参数。操作数组应按 schema 提交。Pi 先移除可选的 `null` 字段,再把单值包成数组:`replacements: [{ ..., flags: null }]` 会省略 `flags`,而 `replacements: { ..., flags: null }` 会把它转为字符串 `"null"`,随后 flags 校验失败。
92
123
 
93
124
  ## 修改被拒绝时
94
125
 
@@ -110,7 +141,7 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
110
141
  }
111
142
  ```
112
143
 
113
- 命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。只有修改成功且文件仍是刚写入的内容时才会启动。命令失败不会回滚文件。TUI 把修改和命令分成两张卡片显示,设置了超时时会显示实时倒计时。
144
+ 命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。Fusion 把命令交给会话前,会确认修改成功且文件仍是刚写入的内容;命令结束后会再次检查。其他写入者仍可能在等待审批或命令执行时改动文件。命令失败不会回滚文件。如果自定义 Bash 调用修改类工具,而目标已在 Fusion 队列中,这次修改会直接报错,不会等待队列。TUI 把修改和命令分成两张卡片显示,设置了超时时会显示实时倒计时。
114
145
 
115
146
  命令卡片使用 Pi 原生工具组件处理鼠标点击和全局展开快捷键,输出更新或屏幕重绘时保留各自的展开状态。内置 Bash 渲染器直接显示命令的原始内容和 details,并将它们保存到会话中以供恢复;当前支持的 Pi API 无法取得其他扩展自定义的 Bash 渲染器。
116
147
 
@@ -144,24 +175,28 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
144
175
  | `grep.defaultContext` | `0` | 每个匹配前后的上下文行数,0–20。 |
145
176
  | `grep.regexTimeoutMs` / `replace.regexTimeoutMs` | `5000` | 单次正则计算的时限,3000–300000 毫秒。 |
146
177
 
147
- 项目中的 `hashlineEdit` 会整体替换全局配置;非法值回退为默认值。修改设置后需重新加载 Pi。以 [配置 schema](src/pi/config.ts) 为准。
178
+ 扩展以 Pi 的工作目录(嵌入时为 SDK 会话的 `cwd`)为基准读取 `.pi/settings.json`,也以它解析工具的相对路径。项目中的 `hashlineEdit` 会整体替换全局配置;非法值回退为默认值。修改设置后需重新加载 Pi。`enabled: false` 保留 Pi 内置工具;`actionFusion: false` 不再为新调用提供 `then_run`,但仍显示已保存的命令卡片。以 [配置 schema](src/pi/config.ts) 为准。
148
179
 
149
180
  ## 输出预算
150
181
 
151
- 输出预算根据所选模型声明的上下文容量计算,不使用剩余上下文。容量已知时,带锚点的 read 行和 grep 载荷各获得每上下文 token 一字节的预算,最高 4 MiB。诊断块获得其四分之一,至少 512 字节;自由文本字段获得诊断块预算的四分之一,至少 128 字节。Grep 预览每四字节字段预算保留一个 UTF-16 单元。定义和回退值位于 [`budgets.ts`](src/pi/budgets.ts)。
182
+ 输出预算根据所选模型声明的上下文容量计算,不使用剩余上下文。容量已知时按每上下文 token 一字节计,最高 4 MiB。带锚点的 read 行获得其四分之一,grep 载荷获得八分之一,各至少 512 字节;384,000 token 的模型每次 read 为 93.8 KiB,每次 grep 为 46.9 KiB。诊断块获得容量的四分之一,至少 512 字节;自由文本字段获得诊断块预算的四分之一,至少 128 字节。Grep 预览按每 100 字节 grep 载荷保留一个 UTF-16 单元,至少 500 个。文件的第一行若放在文件标题之后会超出载荷,就进一步缩窄到放得下为止,`linePreviewLimit` 报告所显示预览中最窄的宽度。定义和回退值位于 [`budgets.ts`](src/pi/budgets.ts)。
152
183
 
153
- 模型容量未知或非法时,默认上限为 read 行 256 KiB、grep 载荷 50 KiB、每个诊断块 16 KiB、每个自由文本字段 4 KiB、每条 grep 预览 500 个 UTF-16 单元。显式设置 `read.maxKiB` 只覆盖 read 上限。每次执行使用开始时取得的预算快照。
184
+ 参数拒绝报告序列化为 JSON 后不超过诊断块预算。编辑失败时,失败条目列表和候选锚点的上下文各按紧凑 JSON 计入一个诊断块,只省略完整条目或整行,并给出省略数量。发给模型的 `then_run.output` 遵守自由文本字段预算;命令卡片保留会话 Bash 的原始结果。
185
+
186
+ 模型容量未知或非法时,默认上限为 read 行 64 KiB、grep 载荷 50 KiB、每个诊断块 16 KiB、每个自由文本字段 4 KiB、每条 grep 预览 500 个 UTF-16 单元。显式设置 `read.maxKiB` 只覆盖 read 上限。每次执行使用开始时取得的预算快照。
154
187
 
155
188
  Read 因默认行数或字节预算截断窗口时会报告 `nextOffset`;只有调用方指定的 `limit` 生效时不额外报告 `nextOffset`。首行放不下时报告 `lineTooLong`,其值为字节上限。Grep 分别报告载荷和行预览的截断,非法 UTF-8 的普通预览不带编辑锚点。
156
189
 
157
- grep 载荷被截断时,如果本次调用返回了上下文行,报告会提示用 `context: 0` 重试,否则提示缩小搜索范围。依据部分预览重写前需检查完整行:`invalidUtf8` 列出的路径使用 Bash,有效 UTF-8 使用 `read`。
190
+ grep 载荷被截断时,只有去掉上下文后能在相同字节预算内多显示至少一条匹配行,报告才提示用 `context: 0` 重试;否则提示缩小搜索范围。依据部分预览重写前需检查完整行:`invalidUtf8` 列出的路径使用 Bash,有效 UTF-8 使用 `read`。
191
+
192
+ 如果 grep 首行放不下列范围标记,预览会保留一个完整字符,用省略号表示省去的正文。只放得下省略号时,`linePreviewLimit` 为零。
158
193
 
159
194
  ## 限制
160
195
 
161
196
  - 锚点是简短的校验和:能发现内容变化和行位移,但可能碰撞,也不能证明模型真的读过这一行。
162
197
  - 只编辑 UTF-8 文本,不支持 UTF-16 和旧式代码页。
163
198
  - 版本检查能发现大多数并发修改,但没有跨进程锁,也没有多文件事务。
164
- - 覆盖写入时保留符号链接、改写其指向的文件;FIFO 等非普通文件和有多个硬链接的文件不会被覆盖。
199
+ - 覆盖写入时保留符号链接、改写其指向的文件。发布前会检查路径是否仍解析到同一位置,以及目标是否仍是只有一个硬链接的普通文件。
165
200
  - Grep 的[搜索限制](src/pi/grep-search.ts)允许 multiline 文件最多 64 MiB、单条物理行最多 64 × 1024² 个 UTF-16 单元。最多使用四个匹配 worker,每个 worker 的 V8 老生代堆上限为 512 MiB;单次正则计算受配置中的超时约束。
166
201
  - 候选发现回退到作用域内所有文件时,累计排入队列的文件大小达到 [256 MiB 扫描预算](src/pi/grep-candidates.ts) 后停止继续加入文件;最后一个文件可以使总量超过该阈值。报告会指出预算是否阻止了后续文件的扫描。Ripgrep 协议记录的[上限为 16 MiB](src/pi/rg-process.ts),其 stderr 最多保留 64 KiB(开头和结尾)。候选分析不支持或超限时会扩大候选范围,最终匹配仍由 JavaScript 决定。
167
202
 
@@ -177,3 +212,11 @@ grep 载荷被截断时,如果本次调用返回了上下文行,报告会提
177
212
  | `npm run test:cartesian` | 耗时较长的笛卡尔积正则矩阵;修改正则翻译或预筛后运行。 |
178
213
 
179
214
  报告字段和错误码定义在 [`report-schema.ts`](src/pi/report-schema.ts)。模块职责见 [`src/core/AGENTS.md`](src/core/AGENTS.md) 与 [`src/pi/AGENTS.md`](src/pi/AGENTS.md)。[`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) 列出了借鉴的技术和测试用例。
215
+
216
+ ## 贡献
217
+
218
+ 提问和报告缺陷请到 [GitHub issues](https://github.com/Criogaid/pi-hashline-edit/issues)。欢迎提交 pull request:请先运行[开发](#开发)一节的检查,并遵循 [`AGENTS.md`](AGENTS.md) 中的提交约定。
219
+
220
+ ## 许可证
221
+
222
+ [MIT](LICENSE)
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
- "description": "Hashline-style file editing for pi — line-anchored edits verified by content hash, replacing oldText/newText matching",
5
+ "description": "Hash-anchored file editing for Pi: line edits cite anchors that are checked against the current file before any write.",
6
6
  "homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
7
7
  "bugs": {
8
8
  "url": "https://github.com/Criogaid/pi-hashline-edit/issues"
@@ -6,7 +6,7 @@ Internal pure engine: no Pi imports and no public API. It trusts input already f
6
6
 
7
7
  - `hash.ts` computes position-dependent line checksums (line number + content → `LINE#HASH`). `lines.ts` handles splitting, line-ending detection, and physical line counts. `text.ts` does strict and lossy UTF-8 decoding and decides which text cannot be written.
8
8
  - `apply.ts` `applyEdits` validates a whole batch of `Edit` ops (see `types.ts`) against a single snapshot: anchor checks, overlap and conflict detection, and shifted-anchor recovery (`AnchorRecovery`: local `shiftRadius` search, then full file). It returns new text or structured anchor failures, throws `OVERLAPPING_EDITS` for an overlap, and never touches the filesystem.
9
- - `regex.ts` builds JavaScript regexes on the LF view (`regexSource`, `buildRegex`) for both grep and replace; neither engine imports the other. `checkRegexArguments` is their shared entry check: it reports flags V8 rejects and compiles regex-mode patterns.
9
+ - `regex.ts` builds JavaScript regexes on the LF view (`regexSource`, `buildRegex`) for both grep and replace; neither engine imports the other. Both tools' argument checks and both engines compile through `buildRegex`, so an engine meets no syntax error that the entry check accepted.
10
10
  - `replace.ts` is replace's engine: literal and JavaScript-regex matching on the LF view, separator restoration, and overlap rejection. `replace-schema.ts` defines the tool's replacement schema and the engine's result schema, with their derived types.
11
11
  - `search.ts` evaluates native JavaScript queries on the LF view and returns bounded physical rows; `search-schema.ts` defines its result.
12
12
  - `search-analysis.ts` parses patterns with regexpp (V8 has already accepted them at tool entry), decides smart case, and derives the literals every match must contain; `case-fold.ts` supplies JavaScript's case equivalence; `character-set.ts` owns character-class sets and shared AST surrogate-pair decoding for both candidate strategies.
@@ -15,5 +15,5 @@ Internal pure engine: no Pi imports and no public API. It trusts input already f
15
15
 
16
16
  ## Constraints
17
17
 
18
- - Own interval algebra, bounded membership caching, and explicit class-string enumeration in `character-set.ts`; derive Unicode properties, `v` sets, and case closure from the running V8 rather than separate Unicode tables. Intersections may enumerate either string operand, subtractions only the left, and unions require every operand. Unknown string properties remain widened.
18
+ - Own interval algebra and bounded membership caching in `character-set.ts`; derive class membership and case closure from the running V8 rather than separate Unicode tables. Grep regexes have no `u` or `v` flag, so a class matches single UTF-16 units and a supplementary character is a surrogate pair.
19
19
  - Derive one necessary file condition in `search-analysis.ts`: an AND keeps its most selective side, because extra rg passes cost more than they save. Preserve every OR alternative, retain necessary prefixes or suffixes when expansion is too large, and cut literals where bytes can differ from the LF view. Unknown constructs widen candidates, never narrow them.
@@ -564,6 +564,19 @@ test("BOM stays at byte zero through first-line edits while anchors retain their
564
564
  assert.equal(result.text, "\uFEFFchanged\ninside\uFEFFcontent\n");
565
565
  });
566
566
 
567
+ test("inserting U+FEFF before the first line → keeps it as content beside the file BOM", () => {
568
+ const text = "\uFEFFfirst\n";
569
+ const body = ["\uFEFFnew"];
570
+ for (const edit of [
571
+ { op: "prepend", body },
572
+ { op: "insert_before", anchor: at(text, 1), body },
573
+ ] satisfies Edit[]) {
574
+ const result = applyEdits(text, [edit], 4, 0);
575
+ assert.ok(result.ok);
576
+ assert.equal(result.text, "\uFEFF\uFEFFnew\nfirst\n", edit.op);
577
+ }
578
+ });
579
+
567
580
  test("replacing a first-line mixed-ending range → preserve gaps and keep one file BOM", () => {
568
581
  const text = "\uFEFFA\r\nB\nC\r\nD\n";
569
582
  const result = applyEdits(
package/src/core/apply.ts CHANGED
@@ -70,13 +70,7 @@ function verifyAnchor(
70
70
  radius: number,
71
71
  ): AnchorFailure | null {
72
72
  const { line, hash } = cited;
73
- if (
74
- line >= 1 &&
75
- line <= lines.length &&
76
- computeLineHash(line, lines[line - 1], hashLen) === hash
77
- ) {
78
- return null;
79
- }
73
+ if (line <= lines.length && computeLineHash(line, lines[line - 1], hashLen) === hash) return null;
80
74
 
81
75
  const candidates: { line: number; hash: string }[] = [];
82
76
  const scan = (start: number, end: number) => {
@@ -253,9 +247,11 @@ export function applyEdits(
253
247
  for (let i = 0; i < op.newLines.length; i++) {
254
248
  const content = op.newLines[i];
255
249
  result.push({
256
- // A copied first-line BOM denotes the existing file header, not a second BOM.
250
+ // Only a replacement of the original first line can carry its copied BOM.
257
251
  content:
258
- bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
252
+ bom && op.lo === 0 && op.hi > 0 && i === 0 && content.startsWith(bom)
253
+ ? content.slice(1)
254
+ : content,
259
255
  separator:
260
256
  i === op.newLines.length - 1 && op.hi > op.lo
261
257
  ? (separators?.[op.hi - 1] ?? "")
@@ -3,31 +3,22 @@ import { test } from "node:test";
3
3
  import { caseVariants } from "./case-fold.ts";
4
4
  import { MAX_UNIT } from "./character-set.ts";
5
5
 
6
- for (const [char, unicode, expected] of [
7
- ["k", false, ["K", "k"]],
8
- ["s", false, ["S", "s"]],
9
- ["k", true, ["K", "k", "K"]],
10
- ["s", true, ["S", "s", "ſ"]],
11
- ["σ", false, ["Σ", "ς", "σ"]],
12
- ["ß", false, ["ß"]],
13
- ["😀", false, ["😀"]],
14
- ["é", true, ["É", "é"]],
15
- ["K", true, ["K", "k", "K"]],
16
- ["σ", true, ["Σ", "ς", "σ"]],
17
- ["𐐀", true, ["𐐀", "𐐨"]],
18
- ["ß", true, ["ß", "ẞ"]],
6
+ for (const [char, expected] of [
7
+ ["k", ["K", "k"]],
8
+ ["s", ["S", "s"]],
9
+ ["σ", ["Σ", "ς", "σ"]],
10
+ ["ß", ["ß"]],
11
+ ["😀", ["😀"]],
19
12
  ] as const) {
20
- test(`${JSON.stringify(char)} unicode=${unicode} → native case variants`, () => {
21
- assert.deepEqual(caseVariants(char, unicode), expected);
22
- for (const flags of unicode ? ["iu", "iv"] : ["i"]) {
23
- const native = new RegExp(`^${char}$`, flags);
24
- for (const candidate of ["K", "k", "K", "S", "s", "ſ", "Σ", "σ", "ς", "ß", "é", "😀"])
25
- assert.equal(
26
- expected.some((value) => value === candidate),
27
- native.test(candidate),
28
- `${flags}: ${candidate}`,
29
- );
30
- }
13
+ test(`${JSON.stringify(char)} → native case variants`, () => {
14
+ assert.deepEqual(caseVariants(char), expected);
15
+ const native = new RegExp(`^${char}$`, "i");
16
+ for (const candidate of ["K", "k", "K", "S", "s", "ſ", "Σ", "σ", "ς", "ß", "é", "😀"])
17
+ assert.equal(
18
+ expected.some((value) => value === candidate),
19
+ native.test(candidate),
20
+ candidate,
21
+ );
31
22
  });
32
23
  }
33
24
 
@@ -39,6 +30,6 @@ test("Cartesian non-Unicode code units → case variants agree with native RegEx
39
30
  const char = String.fromCharCode(unit);
40
31
  const source = `\\u${unit.toString(16).padStart(4, "0")}`;
41
32
  const expected = allUnits.match(new RegExp(source, "gi"));
42
- assert.deepEqual(caseVariants(char, false), expected, source);
33
+ assert.deepEqual(caseVariants(char), expected, source);
43
34
  }
44
35
  });
@@ -6,13 +6,13 @@
6
6
 
7
7
  import { MAX_UNIT, foldRanges } from "./character-set.ts";
8
8
 
9
- /** The characters JavaScript's ignoreCase matches for one character, itself included. */
10
- export function caseVariants(char: string, unicode: boolean): readonly string[] {
9
+ /** The characters a grep regex's ignoreCase matches for one character, itself included. */
10
+ export function caseVariants(char: string): readonly string[] {
11
11
  const point = char.codePointAt(0)!;
12
12
  // Without u, ignoreCase never folds a supplementary character's surrogates.
13
- if (!unicode && point > MAX_UNIT) return [char];
13
+ if (point > MAX_UNIT) return [char];
14
14
  const result: string[] = [];
15
- for (const [low, high] of foldRanges([[point, point]], unicode))
15
+ for (const [low, high] of foldRanges([[point, point]]))
16
16
  for (let code = low; code <= high; code++) result.push(String.fromCodePoint(code));
17
17
  return result;
18
18
  }
@@ -11,11 +11,6 @@ import {
11
11
  import { unsupportedByHost } from "../testing/regex-host.testing.ts";
12
12
 
13
13
  for (const [source, flags] of [
14
- ["\\p{Letter}", "u"],
15
- ["[^\\p{Letter}]", "v"],
16
- ["[\\p{Letter}--[a-z]]", "iv"],
17
- ["(?i:[kſΣ])", "u"],
18
- ["[\\q{ab|😀|}]", "v"],
19
14
  ["\\uD83D", ""],
20
15
  [".", ""],
21
16
  [".", "s"],
@@ -43,7 +38,7 @@ for (const [source, flags] of [
43
38
  "\ud83d",
44
39
  "�",
45
40
  ]) {
46
- const isUnit = flags.includes("u") || flags.includes("v") || char.length === 1;
41
+ const isUnit = char.length === 1;
47
42
  assert.equal(
48
43
  contains(ranges, char.codePointAt(0)!),
49
44
  isUnit && native.exec(char)?.[0] === char,