@criogaid/pi-hashline-edit 0.11.0 → 0.12.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.
- package/README.md +17 -4
- package/README.zh-CN.md +18 -5
- package/package.json +7 -6
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +2 -2
- package/src/core/apply.ts +1 -1
- package/src/core/regex.ts +6 -2
- package/src/core/replace.test.ts +51 -0
- package/src/core/replace.ts +10 -4
- package/src/index.ts +1 -1
- package/src/integration/grep-line-candidates.test.ts +2 -1
- package/src/integration/grep-prefilter-coverage.test.ts +13 -2
- package/src/integration/grep-rg.test.ts +43 -0
- package/src/integration/npm-package.test.ts +12 -10
- package/src/integration/npm-package.testing.ts +148 -1
- package/src/integration/report-replay.test.ts +4 -0
- package/src/pi/AGENTS.md +9 -9
- package/src/pi/argument-validation.test.ts +63 -0
- package/src/pi/argument-validation.ts +21 -31
- package/src/pi/edit-tool.ts +2 -2
- package/src/pi/execute.test.ts +4 -0
- package/src/pi/failure-context.test.ts +1 -1
- package/src/pi/fusion-card.ts +9 -5
- package/src/pi/grep-candidates.ts +5 -4
- package/src/pi/grep-output.ts +10 -3
- package/src/pi/grep-scope.ts +6 -6
- package/src/pi/grep-tool.ts +17 -14
- package/src/pi/grep.test.ts +39 -0
- package/src/pi/mutation-runner.ts +1 -1
- package/src/pi/read.test.ts +45 -0
- package/src/pi/render.test.ts +43 -0
- package/src/pi/report-schema.ts +23 -6
- package/src/pi/report.test.ts +19 -27
- package/src/pi/report.ts +12 -5
- package/src/pi/rg-regex.test.ts +13 -0
- package/src/pi/rg-regex.ts +2 -2
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-
|
|
|
22
22
|
pi install npm:@criogaid/pi-hashline-edit
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
Requires Pi
|
|
25
|
+
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
26
|
|
|
27
27
|
## Quick start
|
|
28
28
|
|
|
@@ -56,13 +56,22 @@ The extension replaces Pi's `read`, `grep`, `edit`, and `write`, and adds `repla
|
|
|
56
56
|
| `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
57
|
| `edit` | Replaces, inserts, or deletes whole lines by anchor. All operations in one call apply to the same snapshot, or none apply. |
|
|
58
58
|
| `replace` | Applies literal or regex substitutions across one file. Every rule must match, and overlapping matches reject the batch. |
|
|
59
|
-
| `write` | Creates a file (`mode: "create"`) or overwrites one (`mode: "overwrite"`), using the content exactly as given. |
|
|
59
|
+
| `write` | Creates a file (`mode: "create"`) or overwrites one (`mode: "overwrite"`), using the content exactly as given. Missing parent directories are created. |
|
|
60
|
+
|
|
61
|
+
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
|
+
|
|
63
|
+
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.
|
|
60
64
|
|
|
61
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.
|
|
62
66
|
|
|
63
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.
|
|
64
68
|
|
|
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.
|
|
70
|
+
|
|
71
|
+
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
|
+
|
|
65
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.
|
|
74
|
+
|
|
66
75
|
Edit operations:
|
|
67
76
|
|
|
68
77
|
| `action` | Effect |
|
|
@@ -75,6 +84,8 @@ One call takes at most [64 operations](src/pi/edit-tool.ts). Ranges in one call
|
|
|
75
84
|
|
|
76
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.
|
|
77
86
|
|
|
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.
|
|
88
|
+
|
|
78
89
|
The model sees each tool's full parameter schema; the definitions live in the tool files under [`src/pi/`](src/pi/).
|
|
79
90
|
|
|
80
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.
|
|
@@ -85,7 +96,7 @@ Argument and anchor validation failures leave the file untouched. The report nam
|
|
|
85
96
|
|
|
86
97
|
A failure during or after publication states `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Follow the report's `next` before retrying: an error after publication can leave the requested change on disk.
|
|
87
98
|
|
|
88
|
-
Argument mistakes, including a reversed range, are reported per field, with what the field means and how to fix it, before any file is touched.
|
|
99
|
+
Argument mistakes, including a reversed range, are reported per field, with what the field means and how to fix it, before any file is touched. A regex syntax error in `grep` or `replace` keeps V8's diagnostic and adds a `fix`: use `literal: true` for exact text, or correct the intended regex. The tool never switches modes automatically.
|
|
89
100
|
|
|
90
101
|
## Action Fusion
|
|
91
102
|
|
|
@@ -143,6 +154,8 @@ When model capacity is unknown or invalid, the defaults are 256 KiB for read row
|
|
|
143
154
|
|
|
144
155
|
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.
|
|
145
156
|
|
|
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.
|
|
158
|
+
|
|
146
159
|
## Limits
|
|
147
160
|
|
|
148
161
|
- Anchors are short checksums: they catch changed and shifted lines, but can collide and do not prove the model read the line.
|
|
@@ -150,7 +163,7 @@ Read reports `nextOffset` when its default line limit or byte budget cuts a wind
|
|
|
150
163
|
- Revision checks catch most concurrent changes, but there is no cross-process lock or multi-file transaction.
|
|
151
164
|
- Overwrites keep symlinks pointing at their target; FIFOs, other non-regular files, and files with multiple hard links are not overwritten.
|
|
152
165
|
- 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.
|
|
153
|
-
- 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). Unsupported or over-limit candidate analysis widens discovery; JavaScript still decides the matches.
|
|
166
|
+
- 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.
|
|
154
167
|
|
|
155
168
|
## Development
|
|
156
169
|
|
package/README.zh-CN.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
## 优势
|
|
10
10
|
|
|
11
|
-
- **改到模型想改的位置。** 每一行都带一个简短的
|
|
11
|
+
- **改到模型想改的位置。** 每一行都带一个简短的 `LINE#HASH` 锚点。模型看过之后文件如果变了,修改会被拒绝,报告会指出这一行移到了哪里。
|
|
12
12
|
- **不靠文本匹配。** 模型不需要原样复述旧文本,空白差异、重复片段和大段代码不再导致修改失败或改错地方。
|
|
13
13
|
- **文件字节不走样。** 保留 BOM、CRLF/LF 换行、文件末尾换行和所有未改动的字节;非法 UTF-8 和 NUL 字节在写入前就被拒绝。
|
|
14
14
|
- **安全写入。** 先写临时文件,再通过 link 或 rename 原子发布;读改写调用绑定实际读取的字节,出错时明确告知文件是否已经发布。
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
pi install npm:@criogaid/pi-hashline-edit
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
需要 Pi
|
|
25
|
+
需要 Pi 1.5.0 或更高版本。扩展只处理本地文件;如果使用远程或自定义存储,把 `hashlineEdit.enabled` 设为 `false` 并重新加载 Pi,即可恢复内置工具。
|
|
26
26
|
|
|
27
27
|
## 快速上手
|
|
28
28
|
|
|
@@ -56,13 +56,22 @@ greet.ts · 3 lines
|
|
|
56
56
|
| `grep` | 用 JavaScript 正则或字面文本搜索文件和目录,按遍历顺序返回带锚点的匹配行、文件路径或计数,设了 limit 时保留该顺序下的前若干条匹配。搜索目录时遵守忽略规则,并跳过 `.git` 和链接目录,在 `path` 指定的目录之下也是如此;在 `path` 中直接指定被忽略的文件或这些目录本身才会搜索。 |
|
|
57
57
|
| `edit` | 按锚点替换、插入或删除整行。一次调用中的所有操作基于同一份快照,要么全部生效,要么全部不生效。 |
|
|
58
58
|
| `replace` | 在单个文件内批量执行字面或正则替换。每条规则都必须有匹配,匹配区域重叠时整批拒绝。 |
|
|
59
|
-
| `write` | 新建文件(`mode: "create"`)或覆盖文件(`mode: "overwrite"
|
|
59
|
+
| `write` | 新建文件(`mode: "create"`)或覆盖文件(`mode: "overwrite"`),内容原样写入,缺失的父目录会一并创建。 |
|
|
60
|
+
|
|
61
|
+
文件路径支持相对路径、绝对路径、`~`、可选的前导 `@` 和 `file://` URL。Windows 还支持 `/c/work/file.txt`、`/mnt/c/work/file.txt`、`/cygdrive/c/work/file.txt` 等 shell 盘符路径。相对路径以工作区目录为基准解析。
|
|
62
|
+
|
|
63
|
+
路径输入会把 U+202F 等部分 Unicode 空格归一化为普通空格。要精确读取文件名中含有 Unicode 空格的文件,请传入经过百分号编码的文件 URL,例如 `file:///home/me/space%E2%80%AFname.txt` 对应含有 U+202F 的文件名。`read` 和 `grep` 返回的路径可以直接传回工具;请保留返回的写法,包括 URL 转义。`read` 将图片和含 NUL 字节的文件交给 Pi 时,也使用相同的路径语法。
|
|
60
64
|
|
|
61
65
|
Grep 按传入顺序访问各个搜索路径,在每个根路径内采用 ripgrep 的有序目录遍历。重复候选路径只在第一次出现时搜索。这不是对所有文件完整路径做全局字典序排序。
|
|
62
66
|
|
|
63
67
|
Grep 用原生 JavaScript 正则匹配 LF 视图。不设 `multiline` 时逐物理行搜索;设为 true 时搜索整个文件,返回匹配涉及的每一物理行。上下文行不计入 `limit`。content 输出会重读匹配文件,略过版本已变的文件;`files` 和 `count` 直接报告搜索时的快照,不做第二次读取。扫描不完整时,报告会给出诊断或扫描上限。
|
|
64
68
|
|
|
69
|
+
`replace` 在相同的 LF 视图上匹配,开头的 BOM 也参与匹配。组装文件时,原 BOM 保持在字节零处,即使匹配包含它或在它前面插入内容。替换包含文件头的匹配时,替换文本开头复制的 BOM 复用原文件头;显式插入或位于正文中的 U+FEFF 字符仍作为内容保留。若需连同 BOM 一起替换完整文件内容,使用 `write`。
|
|
70
|
+
|
|
71
|
+
grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模式会格式化匹配行,隐藏锚点哈希并折叠共有缩进。
|
|
72
|
+
|
|
65
73
|
`edit` 调用先给出定位信息:`path`、`steps`,再是可选的 `then_run`。每个操作先给出动作和范围,再给出替换内容:`action`、`anchor`、可选的 `end`,最后是 `lines`。参数流式输出时,TUI 可以先显示文件和目标范围。
|
|
74
|
+
|
|
66
75
|
`edit` 的操作:
|
|
67
76
|
|
|
68
77
|
| `action` | 效果 |
|
|
@@ -75,6 +84,8 @@ Grep 用原生 JavaScript 正则匹配 LF 视图。不设 `multiline` 时逐物
|
|
|
75
84
|
|
|
76
85
|
在提供方支持时,所有工具都请求约束采样(Pi 的 `constrainedSampling`,即 strict JSON schema),模型因此无法写出 schema 未声明的字段或取值,也无法超出 edit 的操作数上限。这时调用中没用到的可选字段都写 `null`,edit 每个操作里其 `action` 用不到的字段也一样。出于同一原因,grep 的 `pattern`、`path` 和 `glob` 只接受数组;在其他提供方上,Pi 会把单个字符串包成数组。
|
|
77
86
|
|
|
87
|
+
参数转换和接受判定由 Pi 负责;诊断不修改提交的参数。操作数组应按 schema 提交。Pi 先移除可选的 `null` 字段,再把单值包成数组:`replacements: [{ ..., flags: null }]` 会省略 `flags`,而 `replacements: { ..., flags: null }` 会把它转为字符串 `"null"`,随后 flags 校验失败。
|
|
88
|
+
|
|
78
89
|
模型能看到每个工具完整的参数 schema,定义位于 [`src/pi/`](src/pi/) 下的各工具文件。
|
|
79
90
|
|
|
80
91
|
范围操作核对给出的 `anchor`、`end`,不逐行验证区间内部的内容。调用前其他位置的变化不会使未改变的锚点失效;发布前会复核修改操作实际读取的字节,检测到变化时拒绝发布。
|
|
@@ -85,7 +96,7 @@ Grep 用原生 JavaScript 正则匹配 LF 视图。不设 `multiline` 时逐物
|
|
|
85
96
|
|
|
86
97
|
发布期间或发布后的失败会明确标记 `NOT_PUBLISHED`、`PUBLISHED` 或 `UNKNOWN`。重试前应遵循报告的 `next`:发布后的错误可能意味着所需修改已经写入磁盘。
|
|
87
98
|
|
|
88
|
-
|
|
99
|
+
参数错误(包括反向范围)按字段逐条报告,说明字段的含义和修正方法,此时还不会碰任何文件。`grep` 或 `replace` 的正则语法错误保留 V8 原始诊断,并附带 `fix`:原样匹配文本时用 `literal: true`,确实需要正则时修正表达式。工具不会自动切换模式。
|
|
89
100
|
|
|
90
101
|
## Action Fusion
|
|
91
102
|
|
|
@@ -143,6 +154,8 @@ Grep 用原生 JavaScript 正则匹配 LF 视图。不设 `multiline` 时逐物
|
|
|
143
154
|
|
|
144
155
|
Read 因默认行数或字节预算截断窗口时会报告 `nextOffset`;只有调用方指定的 `limit` 生效时不额外报告 `nextOffset`。首行放不下时报告 `lineTooLong`,其值为字节上限。Grep 分别报告载荷和行预览的截断,非法 UTF-8 的普通预览不带编辑锚点。
|
|
145
156
|
|
|
157
|
+
grep 载荷被截断时,如果本次调用返回了上下文行,报告会提示用 `context: 0` 重试,否则提示缩小搜索范围。依据部分预览重写前需检查完整行:`invalidUtf8` 列出的路径使用 Bash,有效 UTF-8 使用 `read`。
|
|
158
|
+
|
|
146
159
|
## 限制
|
|
147
160
|
|
|
148
161
|
- 锚点是简短的校验和:能发现内容变化和行位移,但可能碰撞,也不能证明模型真的读过这一行。
|
|
@@ -150,7 +163,7 @@ Read 因默认行数或字节预算截断窗口时会报告 `nextOffset`;只
|
|
|
150
163
|
- 版本检查能发现大多数并发修改,但没有跨进程锁,也没有多文件事务。
|
|
151
164
|
- 覆盖写入时保留符号链接、改写其指向的文件;FIFO 等非普通文件和有多个硬链接的文件不会被覆盖。
|
|
152
165
|
- Grep 的[搜索限制](src/pi/grep-search.ts)允许 multiline 文件最多 64 MiB、单条物理行最多 64 × 1024² 个 UTF-16 单元。最多使用四个匹配 worker,每个 worker 的 V8 老生代堆上限为 512 MiB;单次正则计算受配置中的超时约束。
|
|
153
|
-
- 候选发现回退到作用域内所有文件时,累计排入队列的文件大小达到 [256 MiB 扫描预算](src/pi/grep-candidates.ts) 后停止继续加入文件;最后一个文件可以使总量超过该阈值。报告会指出预算是否阻止了后续文件的扫描。Ripgrep 协议记录的[上限为 16 MiB](src/pi/rg-process.ts)
|
|
166
|
+
- 候选发现回退到作用域内所有文件时,累计排入队列的文件大小达到 [256 MiB 扫描预算](src/pi/grep-candidates.ts) 后停止继续加入文件;最后一个文件可以使总量超过该阈值。报告会指出预算是否阻止了后续文件的扫描。Ripgrep 协议记录的[上限为 16 MiB](src/pi/rg-process.ts),其 stderr 最多保留 64 KiB(开头和结尾)。候选分析不支持或超限时会扩大候选范围,最终匹配仍由 JavaScript 决定。
|
|
154
167
|
|
|
155
168
|
## 开发
|
|
156
169
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Hashline-style file editing for pi — line-anchored edits verified by content hash, replacing oldText/newText matching",
|
|
6
6
|
"homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
|
|
@@ -30,20 +30,21 @@
|
|
|
30
30
|
"bench": "node bench/throughput.bench.ts"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
+
"@earendil-works/pi-schema": "1.5.0",
|
|
33
34
|
"@eslint-community/regexpp": "4.12.2",
|
|
34
35
|
"@vscode/ripgrep": "1.18.0",
|
|
35
36
|
"jiti": "2.7.0"
|
|
36
37
|
},
|
|
37
38
|
"peerDependencies": {
|
|
38
|
-
"@earendil-works/pi-coding-agent": ">=
|
|
39
|
+
"@earendil-works/pi-coding-agent": ">=1.5.0",
|
|
39
40
|
"typebox": "*"
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
43
|
"@biomejs/biome": "2.5.14",
|
|
43
|
-
"@earendil-works/pi-agent-core": "
|
|
44
|
-
"@earendil-works/pi-ai": "
|
|
45
|
-
"@earendil-works/pi-coding-agent": "
|
|
46
|
-
"@earendil-works/pi-tui": "
|
|
44
|
+
"@earendil-works/pi-agent-core": "1.5.0",
|
|
45
|
+
"@earendil-works/pi-ai": "1.5.0",
|
|
46
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
47
|
+
"@earendil-works/pi-tui": "1.5.0",
|
|
47
48
|
"typebox": "1.3.27",
|
|
48
49
|
"typescript": "^7.0.2"
|
|
49
50
|
},
|
package/src/core/AGENTS.md
CHANGED
|
@@ -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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
package/src/core/apply.test.ts
CHANGED
|
@@ -133,7 +133,7 @@ test("overlapping edit spans → report conflicting operations in input order",
|
|
|
133
133
|
(error: unknown) => {
|
|
134
134
|
assert(error instanceof HashlineError);
|
|
135
135
|
assert.equal(error.errorCode, "OVERLAPPING_EDITS");
|
|
136
|
-
assert.equal(error.message, "Two
|
|
136
|
+
assert.equal(error.message, "Two steps overlap.");
|
|
137
137
|
assert.deepEqual(error.facts?.conflict, ["steps[1]", "steps[2]"]);
|
|
138
138
|
return true;
|
|
139
139
|
},
|
|
@@ -187,7 +187,7 @@ test("insertions sharing a gap → reject the batch", () => {
|
|
|
187
187
|
(error: unknown) => {
|
|
188
188
|
assert(error instanceof HashlineError);
|
|
189
189
|
assert.equal(error.errorCode, "OVERLAPPING_EDITS");
|
|
190
|
-
assert.equal(error.message, "Two
|
|
190
|
+
assert.equal(error.message, "Two steps insert at one position.");
|
|
191
191
|
assert.deepEqual(error.facts?.conflict, ["steps[0]", "steps[1]"]);
|
|
192
192
|
return true;
|
|
193
193
|
},
|
package/src/core/apply.ts
CHANGED
|
@@ -210,7 +210,7 @@ export function applyEdits(
|
|
|
210
210
|
current.lo === current.hi && previous.lo === current.lo && previous.hi === current.hi;
|
|
211
211
|
throw new HashlineError(
|
|
212
212
|
"OVERLAPPING_EDITS",
|
|
213
|
-
repeatedInsertion ? "Two
|
|
213
|
+
repeatedInsertion ? "Two steps insert at one position." : "Two steps overlap.",
|
|
214
214
|
{
|
|
215
215
|
// The first conflicting pair found, ascending.
|
|
216
216
|
facts: {
|
package/src/core/regex.ts
CHANGED
|
@@ -30,7 +30,7 @@ export function checkRegexArguments(
|
|
|
30
30
|
flags: string | undefined,
|
|
31
31
|
literal: boolean,
|
|
32
32
|
patterns: readonly (readonly [field: string, value: unknown])[],
|
|
33
|
-
report: (field: string, reason: string) => void,
|
|
33
|
+
report: (field: string, reason: string, fix?: string) => void,
|
|
34
34
|
): void {
|
|
35
35
|
try {
|
|
36
36
|
buildRegex("", true, flags);
|
|
@@ -44,7 +44,11 @@ export function checkRegexArguments(
|
|
|
44
44
|
try {
|
|
45
45
|
buildRegex(value, false, flags);
|
|
46
46
|
} catch (error) {
|
|
47
|
-
report(
|
|
47
|
+
report(
|
|
48
|
+
field,
|
|
49
|
+
errorMessage(error),
|
|
50
|
+
"For an exact-text match, set literal to true; otherwise correct the regex syntax.",
|
|
51
|
+
);
|
|
48
52
|
}
|
|
49
53
|
}
|
|
50
54
|
}
|
package/src/core/replace.test.ts
CHANGED
|
@@ -4,6 +4,57 @@ import { applyReplacements } from "./replace.ts";
|
|
|
4
4
|
import type { Replacement } from "./replace-schema.ts";
|
|
5
5
|
import { HashlineError } from "./errors.ts";
|
|
6
6
|
|
|
7
|
+
test("replacement at the file start → retains the original BOM at byte zero", async (t) => {
|
|
8
|
+
const cases = [
|
|
9
|
+
{
|
|
10
|
+
name: "zero-width insertion",
|
|
11
|
+
source: "\uFEFFfoo\r\nbar\n",
|
|
12
|
+
find: "^",
|
|
13
|
+
replace: "X",
|
|
14
|
+
expected: "\uFEFFXfoo\r\nbar\n",
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "whole-file replacement",
|
|
18
|
+
source: "\uFEFFfoo",
|
|
19
|
+
find: "^[\\s\\S]*$",
|
|
20
|
+
replace: "X",
|
|
21
|
+
expected: "\uFEFFX",
|
|
22
|
+
},
|
|
23
|
+
{ name: "copied BOM", source: "\uFEFFfoo", find: "^.", replace: "$&X", expected: "\uFEFFXfoo" },
|
|
24
|
+
{ name: "consumed BOM", source: "\uFEFFfoo", find: "^.", replace: "", expected: "\uFEFFfoo" },
|
|
25
|
+
{
|
|
26
|
+
name: "inserted body BOM",
|
|
27
|
+
source: "\uFEFFfoo",
|
|
28
|
+
find: "^",
|
|
29
|
+
replace: "\uFEFF",
|
|
30
|
+
expected: "\uFEFF\uFEFFfoo",
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
name: "capture copied into body",
|
|
34
|
+
source: "\uFEFFfoo",
|
|
35
|
+
find: "^(.*)",
|
|
36
|
+
replace: "X$1",
|
|
37
|
+
expected: "\uFEFFX\uFEFFfoo",
|
|
38
|
+
},
|
|
39
|
+
{ name: "BOM-only file", source: "\uFEFF", find: "^", replace: "X", expected: "\uFEFFX" },
|
|
40
|
+
{
|
|
41
|
+
name: "body BOM",
|
|
42
|
+
source: "foo\uFEFFbar",
|
|
43
|
+
find: "^",
|
|
44
|
+
replace: "X",
|
|
45
|
+
expected: "Xfoo\uFEFFbar",
|
|
46
|
+
},
|
|
47
|
+
];
|
|
48
|
+
for (const { name, source, find, replace, expected } of cases) {
|
|
49
|
+
await t.test(name, () => {
|
|
50
|
+
assert.deepEqual(applyReplacements(source, [{ literal: false, find, replace }]), {
|
|
51
|
+
text: expected,
|
|
52
|
+
count: 1,
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
7
58
|
test("replacement joins beside LF → preserve standalone CR content", async (t) => {
|
|
8
59
|
const literal = (find: string, replace: string): Replacement => ({
|
|
9
60
|
find,
|
package/src/core/replace.ts
CHANGED
|
@@ -88,11 +88,17 @@ export function applyReplacements(
|
|
|
88
88
|
},
|
|
89
89
|
});
|
|
90
90
|
}
|
|
91
|
-
const
|
|
92
|
-
|
|
91
|
+
const bom = source.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
92
|
+
const parts: string[] = [bom];
|
|
93
|
+
let cursor = bom.length;
|
|
93
94
|
for (const change of changes) {
|
|
94
|
-
|
|
95
|
-
|
|
95
|
+
// Keep the original header at byte zero; a copied leading BOM denotes that same header.
|
|
96
|
+
const text =
|
|
97
|
+
bom && change.start === 0 && change.end > 0 && change.text.startsWith(bom)
|
|
98
|
+
? change.text.slice(1)
|
|
99
|
+
: change.text;
|
|
100
|
+
parts.push(source.slice(cursor, Math.max(bom.length, change.start)), text);
|
|
101
|
+
cursor = Math.max(bom.length, change.end);
|
|
96
102
|
}
|
|
97
103
|
parts.push(source.slice(cursor));
|
|
98
104
|
return { text: joinTextFragments(parts), count: changes.length };
|
package/src/index.ts
CHANGED
|
@@ -33,7 +33,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
33
33
|
// read/grep/edit/write stay in place, as if this package were not installed.
|
|
34
34
|
if (config.enabled) {
|
|
35
35
|
const budgets = registerModelBudgets(pi);
|
|
36
|
-
// Saved then_run cards render even when Action Fusion is
|
|
36
|
+
// Saved then_run cards render even when Action Fusion is off.
|
|
37
37
|
const reportProgress = registerFusionCards(pi);
|
|
38
38
|
const fusion = config.actionFusion ? createActionFusionExecutor(reportProgress) : undefined;
|
|
39
39
|
// Every tool returns a report; Pi prints this shared guideline once.
|
|
@@ -85,6 +85,7 @@ const patterns = [
|
|
|
85
85
|
"([[a]--[A]])(?i:\\1)",
|
|
86
86
|
"((?-i:[[a]--[A]]))(?i:\\1)",
|
|
87
87
|
"((?-i:[\\q{a|b}]))(?i:\\1)",
|
|
88
|
+
"([\\q{a}])\\1",
|
|
88
89
|
"((?-i:a))(?i:\\1)",
|
|
89
90
|
"(?i:([\\q{ks|ab}]))\\1",
|
|
90
91
|
"[\\q{\\u0558|a}&&\\p{Letter}]",
|
|
@@ -126,7 +127,7 @@ const patterns = [
|
|
|
126
127
|
"(?m:b$)",
|
|
127
128
|
];
|
|
128
129
|
const processTimeoutMs = 10_000;
|
|
129
|
-
const matrixTimeoutMs =
|
|
130
|
+
const matrixTimeoutMs = 5 * 60_000;
|
|
130
131
|
const candidateLineLimit = 65_536;
|
|
131
132
|
|
|
132
133
|
const sortedRows = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[]) =>
|
|
@@ -41,6 +41,7 @@ const syntaxCases = [
|
|
|
41
41
|
|
|
42
42
|
interface Coverage {
|
|
43
43
|
queries: number;
|
|
44
|
+
rejected: number;
|
|
44
45
|
fullScan: number;
|
|
45
46
|
withHits: number;
|
|
46
47
|
nativeFiles: number;
|
|
@@ -48,7 +49,7 @@ interface Coverage {
|
|
|
48
49
|
}
|
|
49
50
|
|
|
50
51
|
function emptyCoverage(): Coverage {
|
|
51
|
-
return { queries: 0, fullScan: 0, withHits: 0, nativeFiles: 0, candidateFiles: 0 };
|
|
52
|
+
return { queries: 0, rejected: 0, fullScan: 0, withHits: 0, nativeFiles: 0, candidateFiles: 0 };
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
interface CandidateCase {
|
|
@@ -104,6 +105,7 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
|
|
|
104
105
|
const query: GrepQuery = { patterns: [...patterns], flags, multiline, literal: false };
|
|
105
106
|
if (!acceptsNative(query)) {
|
|
106
107
|
rejected++;
|
|
108
|
+
for (const stats of composition === "bare" ? [total, row] : [total]) stats.rejected++;
|
|
107
109
|
continue;
|
|
108
110
|
}
|
|
109
111
|
const prefilter = extractPrefilter(query);
|
|
@@ -159,14 +161,19 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
|
|
|
159
161
|
}),
|
|
160
162
|
);
|
|
161
163
|
for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
|
|
164
|
+
const unsupported = [...syntax]
|
|
165
|
+
.filter(([, stats]) => stats.queries === 0)
|
|
166
|
+
.map(([label]) => label);
|
|
162
167
|
const unwitnessed = [...syntax]
|
|
163
|
-
.filter(([, stats]) => stats.withHits === 0)
|
|
168
|
+
.filter(([, stats]) => stats.queries > 0 && stats.withHits === 0)
|
|
164
169
|
.map(([label]) => label);
|
|
165
170
|
t.diagnostic(
|
|
166
171
|
JSON.stringify({
|
|
167
172
|
files: inputs.length,
|
|
168
173
|
syntaxCases: syntaxCases.length,
|
|
169
174
|
rejected,
|
|
175
|
+
unsupported,
|
|
176
|
+
supportedSyntaxCases: syntax.size - unsupported.length,
|
|
170
177
|
candidateExpressions: cases.length,
|
|
171
178
|
checkedFiles,
|
|
172
179
|
unwitnessed,
|
|
@@ -177,6 +184,10 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
|
|
|
177
184
|
JSON.stringify({ composition, ...stats, possibleFiles: stats.queries * inputs.length }),
|
|
178
185
|
);
|
|
179
186
|
for (const [label, stats] of syntax) t.diagnostic(JSON.stringify({ syntax: label, ...stats }));
|
|
187
|
+
for (const stats of syntax.values())
|
|
188
|
+
assert.equal(stats.queries + stats.rejected, MATRIX_FLAGS.length * 2);
|
|
189
|
+
for (const stats of compositions.values())
|
|
190
|
+
assert.equal(stats.queries + stats.rejected, syntaxCases.length * MATRIX_FLAGS.length * 2);
|
|
180
191
|
// A NUL-only pattern cannot match grep's searchable (non-NUL) file domain.
|
|
181
192
|
assert.deepEqual(unwitnessed, ["NUL"]);
|
|
182
193
|
const requiredLiteral = compositions.get("required literal");
|
|
@@ -533,6 +533,49 @@ test("directory traversal with caller globs → excludes .git while an explicit
|
|
|
533
533
|
}
|
|
534
534
|
});
|
|
535
535
|
|
|
536
|
+
test("case-variant candidate paths → deduplicate aliases while retaining distinct files and later matches", async (t) => {
|
|
537
|
+
const directory = await mkdtemp(join(tmpdir(), "hl-grep-case-dedup-"));
|
|
538
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
539
|
+
const first = join(directory, "MiXeD.txt");
|
|
540
|
+
const variant = join(directory, "mixed.txt");
|
|
541
|
+
const later = join(directory, "later.txt");
|
|
542
|
+
await writeFile(first, "needle\n");
|
|
543
|
+
await writeFile(later, "needle\n");
|
|
544
|
+
let distinct = true;
|
|
545
|
+
try {
|
|
546
|
+
await writeFile(variant, "needle\n", { flag: "wx" });
|
|
547
|
+
} catch (error) {
|
|
548
|
+
if (error instanceof Error && "code" in error && error.code === "EEXIST") distinct = false;
|
|
549
|
+
else throw error;
|
|
550
|
+
}
|
|
551
|
+
const expected = distinct
|
|
552
|
+
? "MiXeD.txt: 1\nmixed.txt: 1\nlater.txt: 1"
|
|
553
|
+
: "MiXeD.txt: 1\nlater.txt: 1";
|
|
554
|
+
const limit = distinct ? 3 : 2;
|
|
555
|
+
const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
|
|
556
|
+
for (const [pattern, multiline] of [
|
|
557
|
+
["needle", false],
|
|
558
|
+
["needle", true],
|
|
559
|
+
[".", true],
|
|
560
|
+
] as const) {
|
|
561
|
+
await t.test(`${pattern}, multiline=${multiline}`, async () => {
|
|
562
|
+
const result = await callTool(tool, {
|
|
563
|
+
path: [first, variant, later],
|
|
564
|
+
pattern: [pattern],
|
|
565
|
+
literal: false,
|
|
566
|
+
multiline,
|
|
567
|
+
outputMode: "count",
|
|
568
|
+
limit,
|
|
569
|
+
});
|
|
570
|
+
assert.equal(result.isError, undefined);
|
|
571
|
+
assert.equal(result.content[0].type, "text");
|
|
572
|
+
assert.equal(result.content[0].text.split("\n{\n")[0].replaceAll("\\", "/"), expected);
|
|
573
|
+
assert.equal(grepCounts(result).matches, limit);
|
|
574
|
+
assert.equal(grepCounts(result).files, limit);
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
|
|
536
579
|
test("explicit file with different case and a glob → admits the same file on a case-insensitive filesystem", async (t) => {
|
|
537
580
|
const directory = await mkdtemp(join(tmpdir(), "hl-grep-case-admission-"));
|
|
538
581
|
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
@@ -5,13 +5,15 @@ import { test } from "node:test";
|
|
|
5
5
|
import { installedExtension } from "../testing/installation.testing.ts";
|
|
6
6
|
import { runTestProcess } from "../testing/process.testing.ts";
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
8
|
+
for (const source of ["source", "packed"] as const) {
|
|
9
|
+
test(`${source} installation without devDependencies → real Pi workflow and argument diagnostics`, async (t) => {
|
|
10
|
+
const installation = await installedExtension(t, source);
|
|
11
|
+
if (source === "packed") await access(join(installation.packageDir, "THIRD_PARTY_NOTICES.md"));
|
|
12
|
+
await runTestProcess(
|
|
13
|
+
process.execPath,
|
|
14
|
+
[fileURLToPath(new URL("./npm-package.testing.ts", import.meta.url)), installation.entry],
|
|
15
|
+
installation.root,
|
|
16
|
+
installation.agentDir,
|
|
17
|
+
);
|
|
18
|
+
});
|
|
19
|
+
}
|