@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 +18 -12
- package/README.zh-CN.md +18 -12
- package/package.json +8 -1
- package/src/core/AGENTS.md +3 -1
- package/src/core/apply.ts +110 -117
- package/src/core/character-set.ts +2 -3
- package/src/core/copy-span.ts +15 -0
- package/src/core/errors.ts +24 -9
- package/src/core/lines.ts +71 -17
- package/src/core/ranges.ts +5 -4
- package/src/core/replace-schema.ts +3 -1
- package/src/core/replace.ts +50 -29
- package/src/core/search-analysis.ts +21 -22
- package/src/core/search.ts +15 -32
- package/src/core/types.ts +3 -0
- package/src/index.ts +47 -39
- package/src/pi/AGENTS.md +30 -19
- package/src/pi/action-fusion.ts +284 -211
- package/src/pi/argument-diagnostics.ts +50 -37
- package/src/pi/argument-error.ts +2 -2
- package/src/pi/argument-validation.ts +163 -66
- package/src/pi/budgets.ts +12 -0
- package/src/pi/diagnostic-buffer.ts +12 -11
- package/src/pi/edit-tool.ts +138 -115
- package/src/pi/error-text.ts +10 -2
- package/src/pi/failure-context.ts +24 -37
- package/src/pi/file-commit.ts +131 -164
- package/src/pi/file-read.ts +122 -31
- package/src/pi/fusion-arguments.ts +214 -0
- package/src/pi/fusion-card.ts +102 -60
- package/src/pi/grep-candidates.ts +35 -22
- package/src/pi/grep-output.ts +197 -190
- package/src/pi/grep-render.ts +22 -13
- package/src/pi/grep-reread.ts +7 -6
- package/src/pi/grep-scope.ts +31 -16
- package/src/pi/grep-search.ts +56 -47
- package/src/pi/grep-tool.ts +35 -33
- package/src/pi/grep-worker.ts +3 -4
- package/src/pi/mutation-diff.ts +238 -0
- package/src/pi/mutation-result.ts +102 -79
- package/src/pi/mutation-runner.ts +107 -84
- package/src/pi/native-bash.ts +41 -0
- package/src/pi/path.ts +59 -6
- package/src/pi/read-tool.ts +173 -138
- package/src/pi/regex-worker.ts +14 -8
- package/src/pi/render.ts +101 -54
- package/src/pi/replace-regex.ts +1 -1
- package/src/pi/replace-tool.ts +14 -7
- package/src/pi/report-cause.ts +34 -17
- package/src/pi/report-schema.ts +184 -85
- package/src/pi/report.ts +133 -64
- package/src/pi/rg-process.ts +68 -48
- package/src/pi/schema.ts +4 -0
- package/src/pi/text-stream.ts +81 -87
- package/src/pi/workspace-cwd.js +2 -0
- package/src/pi/workspace.ts +46 -0
- package/src/pi/write-tool.ts +19 -13
- package/src/core/apply.test.ts +0 -644
- package/src/core/case-fold.test.ts +0 -35
- package/src/core/character-set.test.ts +0 -97
- package/src/core/errors.test.ts +0 -39
- package/src/core/hash.test.ts +0 -64
- package/src/core/lines.test.ts +0 -63
- package/src/core/ranges.test.ts +0 -123
- package/src/core/replace.test.ts +0 -187
- package/src/core/search-analysis.test.ts +0 -210
- package/src/core/search-matrix.test.ts +0 -64
- package/src/core/search-matrix.testing.ts +0 -171
- package/src/core/search.test.ts +0 -132
- package/src/core/text.test.ts +0 -52
- package/src/integration/config-registration.test.ts +0 -291
- package/src/integration/fusion-dispatch.test.ts +0 -320
- package/src/integration/grep-errors.test.ts +0 -81
- package/src/integration/grep-flags.test.ts +0 -76
- package/src/integration/grep-js-completeness.test.ts +0 -278
- package/src/integration/grep-line-candidates.test.ts +0 -201
- package/src/integration/grep-matrix.test.ts +0 -118
- package/src/integration/grep-order.test.ts +0 -78
- package/src/integration/grep-path-matrix.test.ts +0 -128
- package/src/integration/grep-prefilter-coverage.test.ts +0 -204
- package/src/integration/grep-process-limits.test.ts +0 -122
- package/src/integration/grep-regex.test.ts +0 -412
- package/src/integration/grep-rg.test.ts +0 -1659
- package/src/integration/grep-scan-budget.test.ts +0 -111
- package/src/integration/grep-translation.test.ts +0 -199
- package/src/integration/large-text.test.ts +0 -70
- package/src/integration/model-budget-lifecycle.test.ts +0 -186
- package/src/integration/mutation-file-types.test.ts +0 -30
- package/src/integration/mutation-file-types.testing.ts +0 -33
- package/src/integration/npm-package.test.ts +0 -19
- package/src/integration/npm-package.testing.ts +0 -243
- package/src/integration/publication-read-changes.test.ts +0 -454
- package/src/integration/read-changes.test.ts +0 -98
- package/src/integration/replace-package.test.ts +0 -22
- package/src/integration/replace-package.testing.ts +0 -36
- package/src/integration/replace-worker-boundary.test.ts +0 -127
- package/src/integration/report-replay.test.ts +0 -91
- package/src/integration/utf8-errors.test.ts +0 -46
- package/src/pi/action-fusion.test.ts +0 -659
- package/src/pi/action-fusion.testing.ts +0 -38
- package/src/pi/anchor-format.test.ts +0 -124
- package/src/pi/argument-error.testing.ts +0 -46
- package/src/pi/argument-format.test.ts +0 -196
- package/src/pi/argument-validation.test.ts +0 -1007
- package/src/pi/codemode.test.ts +0 -101
- package/src/pi/config.test.ts +0 -204
- package/src/pi/diagnostic-buffer.test.ts +0 -115
- package/src/pi/directory-sync.test.ts +0 -57
- package/src/pi/execute.test.ts +0 -1257
- package/src/pi/extension-loading.test.ts +0 -14
- package/src/pi/extension-loading.testing.ts +0 -3
- package/src/pi/failure-context.test.ts +0 -370
- package/src/pi/failure-path.test.ts +0 -289
- package/src/pi/file-commit.test.ts +0 -628
- package/src/pi/file-read.test.ts +0 -29
- package/src/pi/file-snapshot.test.ts +0 -22
- package/src/pi/fusion-card-interaction.test.ts +0 -143
- package/src/pi/fusion-card.test.ts +0 -353
- package/src/pi/grep-candidates.test.ts +0 -26
- package/src/pi/grep-matrix.test.ts +0 -68
- package/src/pi/grep-order.test.ts +0 -447
- package/src/pi/grep-output.testing.ts +0 -24
- package/src/pi/grep-rg.testing.ts +0 -73
- package/src/pi/grep.test.ts +0 -1670
- package/src/pi/model-budgets.test.ts +0 -96
- package/src/pi/mutation-outcome.testing.ts +0 -20
- package/src/pi/mutation-result.test.ts +0 -96
- package/src/pi/output-budgets.test.ts +0 -221
- package/src/pi/pi.test.ts +0 -158
- package/src/pi/read-delegation.test.ts +0 -119
- package/src/pi/read.test.ts +0 -735
- package/src/pi/regex-worker.test.ts +0 -42
- package/src/pi/registration.test.ts +0 -549
- package/src/pi/render.test.ts +0 -841
- package/src/pi/replace.test.ts +0 -634
- package/src/pi/report-failure.testing.ts +0 -27
- package/src/pi/report.test.ts +0 -533
- package/src/pi/result-safety.test.ts +0 -597
- package/src/pi/rg-process.test.ts +0 -133
- package/src/pi/rg-regex.test.ts +0 -40
- package/src/pi/text-stream.test.ts +0 -281
- package/src/pi/tool-call.testing.ts +0 -61
- package/src/pi/tool-factories.testing.ts +0 -59
- package/src/pi/write.test.ts +0 -256
- package/src/testing/extension-loader.testing.ts +0 -24
- package/src/testing/installation.testing.ts +0 -77
- package/src/testing/process.testing.ts +0 -33
- package/src/testing/regex-host.testing.ts +0 -20
- package/src/testing/regex-translation-corpus.ts +0 -267
- package/src/testing/rg-line-listing.fixture.mjs +0 -7
- package/src/testing/run-tests.ts +0 -47
- package/src/testing/session.testing.ts +0 -127
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ pi install npm:@criogaid/pi-hashline-edit
|
|
|
41
41
|
|
|
42
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.
|
|
43
43
|
|
|
44
|
-
To locate the workspace during registration, the extension
|
|
44
|
+
To locate the workspace during registration, the extension queries the Pi loader's working directory. On Windows it uses Windows Script Host (`cscript.exe`) and falls back to Windows PowerShell if the script cannot return a valid path. On macOS and Linux it uses `/bin/pwd`.
|
|
45
45
|
|
|
46
46
|
## Usage
|
|
47
47
|
|
|
@@ -65,29 +65,33 @@ The model copies an anchor into `edit`:
|
|
|
65
65
|
|
|
66
66
|
The edit succeeds only if line 2 still has that content. The TUI shows the diff; the model receives a short JSON report.
|
|
67
67
|
|
|
68
|
+
The `edit` and `replace` cards use unchanged rows from the mutation to bound the diff. A shared BOM stays with the file, so the first row's copied body can identify a surviving duplicate. A copied last-line body can also identify which duplicate survives when adding or removing its neighbor changes the line terminator. Each changed range aligns up to 128 line additions and deletions combined. If alignment exceeds that limit, the card keeps proven matches and shows the remaining original and replacement rows as blocks.
|
|
69
|
+
|
|
68
70
|
## Tools
|
|
69
71
|
|
|
70
72
|
The extension replaces Pi's `read`, `grep`, `edit`, and `write`, and adds `replace`.
|
|
71
73
|
|
|
72
74
|
| Tool | What it does |
|
|
73
75
|
| --- | --- |
|
|
74
|
-
| `read` | Shows UTF-8 text with anchors, paginated within the model's output budget
|
|
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. |
|
|
76
|
+
| `read` | Shows UTF-8 text with anchors after a header line, paginated within the model's output budget; CRLF shows as LF and standalone CR as `␍`. For a file the model will not edit, `anchors: false` returns the lines alone, without the header or row prefixes, saving about a third of the tokens. Images and files containing NUL bytes go to Pi's built-in read without a Hashline header. |
|
|
77
|
+
| `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 except for files and directories a positive `glob` matches, 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. |
|
|
76
78
|
| `edit` | Replaces, inserts, or deletes whole lines by anchor. All operations in one call apply to the same snapshot, or none apply. |
|
|
77
79
|
| `replace` | Applies literal or regex substitutions across one file. Every rule must match, and overlapping matches reject the batch. |
|
|
78
80
|
| `write` | Creates a file (`mode: "create"`) or overwrites one (`mode: "overwrite"`), using the content exactly as given. Missing parent directories are created. |
|
|
79
81
|
|
|
82
|
+
Scripts that call these tools, such as Pi's codemode, receive each successful result as one object in place of the result text: the fields its report states, preceded for `read` and `grep` by the payload as `text`. The object also has the facts the report leaves out because the payload or the call already shows them: every `grep` result has `matches` and `files`; a `read` that returns at least one line has `nextOffset` whenever lines remain after it, including when the caller's `limit` ends the window (a first line too long to fit returns no line, so the result has `lineTooLong` and no `nextOffset`); and a change with `then_run` includes its status and any native Bash structured fields. For example, a read cut by its default line limit is `{ text, nextOffset, next }` and a created file is `{ publication }`; reading an image gives Pi's image block, and a file containing NUL bytes gives `{ text }` with Pi's own read output, whose continuation notice is part of that text. A `write`, `edit`, or `replace` whose result equals the file's current content is not a failure: the call resolves with `publication: "NOT_PUBLISHED"`, and nothing is written. A failed call rejects with its report text.
|
|
83
|
+
|
|
80
84
|
### Paths
|
|
81
85
|
|
|
82
86
|
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.
|
|
83
87
|
|
|
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.
|
|
88
|
+
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`, and the paths a report lists in `missing`, use a spelling that can be passed back to the tools, with `/` as the separator on every platform; keep that spelling, including any URL escapes. The same path syntax applies when `read` delegates images or NUL-containing files to Pi.
|
|
85
89
|
|
|
86
90
|
### grep
|
|
87
91
|
|
|
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
|
|
92
|
+
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` (paths beyond the diagnostic block are counted in `omittedMissing`), 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.
|
|
89
93
|
|
|
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
|
|
94
|
+
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`; when they are shown, a `--` row separates groups of rows that are not adjacent lines of one file. 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.
|
|
91
95
|
|
|
92
96
|
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.
|
|
93
97
|
|
|
@@ -119,7 +123,7 @@ The model sees each tool's full parameter schema; the definitions live in the to
|
|
|
119
123
|
|
|
120
124
|
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
125
|
|
|
122
|
-
Pi
|
|
126
|
+
The tool checks a structured-clone snapshot of the arguments using Pi's coercion rules, then hands that snapshot to Pi for coercion and validation. A `tool_call` hook receives those converted values. The tool checks a fresh snapshot after the hook and uses it for execution. Hook edits must satisfy the tool's schema and operation rules. For ordinary objects and arrays, both snapshots copy enumerable own string-keyed properties. Arrays in either snapshot must have no holes or named properties. Both checks follow the item schema for a singleton and report its original path, for example `steps.lines[1]`. A singleton left by a hook still fails schema validation at the array field. Before file access, the tool reports `INVALID_ARGUMENTS` for invalid arguments, with only the first offending path for an array shape error. 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.
|
|
123
127
|
|
|
124
128
|
## When an edit is rejected
|
|
125
129
|
|
|
@@ -127,7 +131,7 @@ Argument and anchor validation failures leave the file untouched. The report nam
|
|
|
127
131
|
|
|
128
132
|
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.
|
|
129
133
|
|
|
130
|
-
|
|
134
|
+
Errors in the file operation's arguments, including a reversed range, are reported per field before file access, with the field's meaning and how to fix it. 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.
|
|
131
135
|
|
|
132
136
|
## Action Fusion
|
|
133
137
|
|
|
@@ -141,9 +145,11 @@ Argument mistakes, including a reversed range, are reported per field, with what
|
|
|
141
145
|
}
|
|
142
146
|
```
|
|
143
147
|
|
|
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
|
|
148
|
+
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. Invalid `then_run` arguments still let a valid file operation complete. The result states the actual `publication`, reports `then_run.status` as `failed`, and shows the argument diagnostic. Bash is not started. To retry, correct the arguments and call `bash` directly. A failing command never rolls back the file. The model receives the final session Bash text and image content blocks in order, with native formatting, limits and truncation, followed by a separate change report whose `then_run` states the command's status. Hashline does not apply its field budget to these blocks. Scripts receive `then_run.status` and, when supplied by Bash, `output` (raw stdout/stderr, possibly empty), `truncated`, optional `full_output_path`, `exit_code`, and `wall_time_seconds`. A permission block, timeout, skipped command, or override without a native structured result can provide status alone; diagnostics appear in content. 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 countdown from the effective Bash timeout once Bash reports execution progress.
|
|
149
|
+
|
|
150
|
+
Cancelling a mutation while it waits in the Fusion queue stops that call before it writes. The earlier mutation and command keep their place in the queue.
|
|
145
151
|
|
|
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
|
|
152
|
+
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 content, output path, and truncation information. Command cards save these values for session restore. Custom Bash renderer overrides are not exposed by the supported Pi API.
|
|
147
153
|
|
|
148
154
|
## Configuration
|
|
149
155
|
|
|
@@ -181,11 +187,11 @@ The Pi workspace (the SDK session's `cwd` when embedded) is the base for both `.
|
|
|
181
187
|
|
|
182
188
|
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).
|
|
183
189
|
|
|
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
|
|
190
|
+
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; so do replace's list of unmatched rules and the list of missing paths.
|
|
185
191
|
|
|
186
192
|
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.
|
|
187
193
|
|
|
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.
|
|
194
|
+
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. With `anchors: false`, an `offset` past the last line fails with `OFFSET_PAST_END` and the file's `totalLines`; an empty file read from its first line returns empty text. Grep reports payload and preview truncation separately, and plain previews for invalid UTF-8 never carry edit anchors.
|
|
189
195
|
|
|
190
196
|
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
197
|
|
package/README.zh-CN.md
CHANGED
|
@@ -41,7 +41,7 @@ pi install npm:@criogaid/pi-hashline-edit
|
|
|
41
41
|
|
|
42
42
|
需要 Pi 1.5.0 或更高版本。扩展只处理本地文件;如果使用远程或自定义存储,把 `hashlineEdit.enabled` 设为 `false` 并重新加载 Pi,即可恢复内置工具。
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
注册时,扩展查询 Pi 加载器的工作目录。Windows 使用 Windows 脚本宿主(`cscript.exe`),脚本无法返回有效路径时回退到 Windows PowerShell。macOS 和 Linux 使用 `/bin/pwd`。
|
|
45
45
|
|
|
46
46
|
## 用法
|
|
47
47
|
|
|
@@ -65,29 +65,33 @@ greet.ts · 3 lines
|
|
|
65
65
|
|
|
66
66
|
只有第 2 行内容仍然一致时修改才会成功。TUI 显示 diff,模型收到一份简短的 JSON 报告。
|
|
67
67
|
|
|
68
|
+
`edit` 和 `replace` 卡片用操作中原样复制的整行划分 diff 区段。修改前后都有的 BOM 留在文件头,原样复制的首行正文仍可以确定保留的是哪一条重复行。增删相邻行导致末行换行符变化时,原样复制的末行正文也可以确定保留的是哪一条重复行。每个区段按增删合计最多 128 行尝试对齐。超过上限时,卡片保留来源已确定的行,其余修改前后的行成块显示。
|
|
69
|
+
|
|
68
70
|
## 工具
|
|
69
71
|
|
|
70
72
|
扩展替换 Pi 的 `read`、`grep`、`edit`、`write`,并新增 `replace`。
|
|
71
73
|
|
|
72
74
|
| 工具 | 作用 |
|
|
73
75
|
| --- | --- |
|
|
74
|
-
| `read` | 显示带锚点的 UTF-8
|
|
75
|
-
| `grep` | 用 JavaScript 正则或字面文本搜索文件和目录,按遍历顺序返回带锚点的匹配行、文件路径或计数,设了 limit
|
|
76
|
+
| `read` | 显示带锚点的 UTF-8 文本,首行是标题,按模型的输出预算分页;CRLF 显示为 LF,独立的回车符显示为 `␍`。对不打算编辑的文件传 `anchors: false` 时只返回各行,没有标题和行前缀,token 约少三分之一。图片和含 NUL 字节的文件交给 Pi 内置的 read,不添加 Hashline 标题。 |
|
|
77
|
+
| `grep` | 用 JavaScript 正则或字面文本搜索文件和目录,按遍历顺序返回带锚点的匹配行、文件路径或计数,设了 limit 时保留该顺序下的前若干条匹配。搜索目录时遵守忽略规则(正向 `glob` 匹配到的文件和目录除外),并跳过 `.git` 和链接目录,在 `path` 指定的目录之下也是如此;在 `path` 中直接指定被忽略的文件或这些目录本身时会搜索它。 |
|
|
76
78
|
| `edit` | 按锚点替换、插入或删除整行。一次调用中的所有操作基于同一份快照,要么全部生效,要么全部不生效。 |
|
|
77
79
|
| `replace` | 在单个文件内批量执行字面或正则替换。每条规则都必须有匹配,匹配区域重叠时整批拒绝。 |
|
|
78
80
|
| `write` | 新建文件(`mode: "create"`)或覆盖文件(`mode: "overwrite"`),内容原样写入,缺失的父目录会一并创建。 |
|
|
79
81
|
|
|
82
|
+
调用这些工具的脚本(例如 Pi 的 codemode)拿到的每个成功结果是一个对象,而不是结果文本:对象里是报告的各个字段,`read` 和 `grep` 另把正文放在 `text` 里。报告因为正文或调用本身已经体现而省略的事实,对象里也有:`grep` 的结果始终带 `matches` 和 `files`;`read` 至少返回一行且其后还有行时始终带 `nextOffset`,包括窗口由调用方的 `limit` 截止的情况(首行过长放不下时不返回任何行,结果带 `lineTooLong`,不带 `nextOffset`);带 `then_run` 的修改包含命令状态和 Bash 提供的原生结构化字段。例如,被默认行数截断的读取是 `{ text, nextOffset, next }`,新建文件是 `{ publication }`;读图片时拿到 Pi 的图片块;读含 NUL 字节的文件时拿到 `{ text }`,内容是 Pi 原版 read 的输出,续读提示写在这段文本里。`write`、`edit`、`replace` 的结果和文件现有内容相同时不算失败:调用正常返回,`publication` 是 `NOT_PUBLISHED`,没有写入任何内容。调用失败时脚本收到异常,内容是报告文本。
|
|
83
|
+
|
|
80
84
|
### 路径
|
|
81
85
|
|
|
82
86
|
文件路径支持相对路径、绝对路径、`~`、可选的前导 `@` 和 `file://` URL。Windows 还支持 `/c/work/file.txt`、`/mnt/c/work/file.txt`、`/cygdrive/c/work/file.txt` 等 shell 盘符路径。相对路径以工作区目录为基准解析。
|
|
83
87
|
|
|
84
|
-
路径输入会把 U+202F 等部分 Unicode 空格归一化为普通空格。要精确读取文件名中含有 Unicode 空格的文件,请传入经过百分号编码的文件 URL,例如 `file:///home/me/space%E2%80%AFname.txt` 对应含有 U+202F 的文件名。`read` 和 `grep`
|
|
88
|
+
路径输入会把 U+202F 等部分 Unicode 空格归一化为普通空格。要精确读取文件名中含有 Unicode 空格的文件,请传入经过百分号编码的文件 URL,例如 `file:///home/me/space%E2%80%AFname.txt` 对应含有 U+202F 的文件名。`read` 和 `grep` 返回的路径,以及报告的 `missing` 里列出的路径,都可以直接传回工具,在所有平台上都用 `/` 作分隔符;请保留返回的写法,包括 URL 转义。`read` 将图片和含 NUL 字节的文件交给 Pi 时,也使用相同的路径语法。
|
|
85
89
|
|
|
86
90
|
### grep
|
|
87
91
|
|
|
88
|
-
Grep 按传入顺序访问各个搜索路径,在每个根路径内采用 ripgrep 的有序目录遍历。重复候选路径只在第一次出现时搜索。这不是对所有文件完整路径做全局字典序排序。不存在的路径列在报告的 `missing`
|
|
92
|
+
Grep 按传入顺序访问各个搜索路径,在每个根路径内采用 ripgrep 的有序目录遍历。重复候选路径只在第一次出现时搜索。这不是对所有文件完整路径做全局字典序排序。不存在的路径列在报告的 `missing` 中(超出诊断块的路径计入 `omittedMissing`),其余路径照常搜索;只有全部路径都不存在,或某个不存在的路径含通配符时,调用才以 `PATH_NOT_FOUND` 失败。
|
|
89
93
|
|
|
90
|
-
Grep 用带 `m` 标志的原生 JavaScript 正则匹配 LF 视图(把 CRLF 换行显示为 LF 的文件文本);`ignoreCase` 会加上 `i`,grep 不接受其他标志。不设 `multiline` 时逐物理行搜索;设为 true 时搜索整个文件,返回匹配涉及的每一物理行。上下文行不计入 `limit
|
|
94
|
+
Grep 用带 `m` 标志的原生 JavaScript 正则匹配 LF 视图(把 CRLF 换行显示为 LF 的文件文本);`ignoreCase` 会加上 `i`,grep 不接受其他标志。不设 `multiline` 时逐物理行搜索;设为 true 时搜索整个文件,返回匹配涉及的每一物理行。上下文行不计入 `limit`;显示上下文行时,同一文件里行号不相邻的两组行之间有一行 `--`。content 输出会重读匹配文件,略过版本(文件字节的 SHA-256)已变的文件;`files` 和 `count` 直接报告搜索时的快照,不做第二次读取。扫描不完整时,报告会给出诊断或扫描上限。
|
|
91
95
|
|
|
92
96
|
grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模式会格式化匹配行,隐藏锚点哈希并折叠共有缩进。
|
|
93
97
|
|
|
@@ -119,7 +123,7 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
119
123
|
|
|
120
124
|
在提供方支持时,所有工具都请求约束采样(Pi 的 `constrainedSampling`:提供方把模型输出限制在工具的 strict JSON schema 内),模型因此无法写出 schema 未声明的字段或取值,也无法超出 edit 的操作数上限。这时调用中没用到的可选字段都写 `null`,edit 每个操作里其 `action` 用不到的字段也一样。出于同一原因,grep 的 `pattern`、`path` 和 `glob` 只接受数组;在其他提供方上,Pi 会把单个字符串包成数组。
|
|
121
125
|
|
|
122
|
-
|
|
126
|
+
工具用 Pi 的转换规则检查参数的结构化克隆快照,再把该快照交给 Pi 转换并校验。`tool_call` 钩子收到转换后的值。工具在钩子运行后重新取快照,校验通过后用它执行操作。钩子改写的参数也必须符合工具的 schema 和操作规则。对普通对象和数组,两份快照均复制自有、可枚举的字符串键属性,其中的数组不能有空洞或命名属性。两次检查都会按元素的 schema 检查单值,并报告原参数中的路径,例如 `steps.lines[1]`。如果钩子在数组字段留下单值,该字段仍无法通过 schema 校验。参数无效时,工具在访问文件前返回 `INVALID_ARGUMENTS`,数组形状错误只报告首个出错路径。操作数组应按 schema 提交。Pi 先移除可选的 `null` 字段,再把单值包成数组:`replacements: [{ ..., flags: null }]` 会省略 `flags`,而 `replacements: { ..., flags: null }` 会把它转为字符串 `"null"`,随后 flags 校验失败。
|
|
123
127
|
|
|
124
128
|
## 修改被拒绝时
|
|
125
129
|
|
|
@@ -127,7 +131,7 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
127
131
|
|
|
128
132
|
发布期间或发布后的失败会明确标记 `NOT_PUBLISHED`、`PUBLISHED` 或 `UNKNOWN`。重试前应遵循报告的 `next`:发布后的错误可能意味着所需修改已经写入磁盘。
|
|
129
133
|
|
|
130
|
-
|
|
134
|
+
文件操作本身的参数有误(包括范围写反)时,工具在访问文件前逐项报告字段的含义和修正方法。`grep` 或 `replace` 的正则语法错误保留 V8 原始诊断,并附带 `fix`:原样匹配文本时用 `literal: true`,确实需要正则时修正表达式。工具不会自动切换模式。
|
|
131
135
|
|
|
132
136
|
## Action Fusion
|
|
133
137
|
|
|
@@ -141,9 +145,11 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
141
145
|
}
|
|
142
146
|
```
|
|
143
147
|
|
|
144
|
-
命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。Fusion
|
|
148
|
+
命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。Fusion 把命令交给会话前,会确认修改成功且文件仍是刚写入的内容;命令结束后会再次检查。其他写入者仍可能在等待审批或命令执行时改动文件。`then_run` 参数有误时,有效的文件操作仍会完成。结果里的 `publication` 表示文件的实际发布状态,`then_run.status` 为 `failed`,并附有具体的参数诊断。Bash 不会启动。要重试命令,修正参数后单独调用 `bash` 即可。命令失败不会回滚文件。模型按顺序收到会话 Bash 最终结果的文本和图片内容块,保留原生格式、限制和截断,后面是独立的修改报告,其中 `then_run` 写明命令状态。Hashline 不对这些内容块应用字段预算。脚本收到 `then_run.status`,以及 Bash 提供的原生结构化字段:`output`(原始标准输出和标准错误,可以为空)、`truncated`、可选的 `full_output_path`、`exit_code` 和 `wall_time_seconds`。审批拦截、超时、跳过命令或未提供原生结构化结果的覆盖可以只有状态;诊断信息显示在内容中。如果自定义 Bash 调用修改类工具,而目标已在 Fusion 队列中,这次修改会直接报错,不会等待队列。TUI 把修改和命令分成两张卡片显示,Bash 发出第一条执行进度后,命令卡片按实际生效的超时值倒计时。
|
|
149
|
+
|
|
150
|
+
修改调用在 Fusion 队列中等待时可以取消,取消后不会写入文件。前面的修改和命令仍占有队列。
|
|
145
151
|
|
|
146
|
-
命令卡片使用 Pi 原生工具组件处理鼠标点击和全局展开快捷键,输出更新或屏幕重绘时保留各自的展开状态。内置 Bash
|
|
152
|
+
命令卡片使用 Pi 原生工具组件处理鼠标点击和全局展开快捷键,输出更新或屏幕重绘时保留各自的展开状态。内置 Bash 渲染器直接显示命令的内容、完整输出路径和截断信息。命令卡片保存这些值以供会话恢复;当前支持的 Pi API 无法取得其他扩展自定义的 Bash 渲染器。
|
|
147
153
|
|
|
148
154
|
## 配置
|
|
149
155
|
|
|
@@ -181,11 +187,11 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
181
187
|
|
|
182
188
|
输出预算根据所选模型声明的上下文容量计算,不使用剩余上下文。容量已知时按每上下文 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)。
|
|
183
189
|
|
|
184
|
-
参数拒绝报告序列化为 JSON 后不超过诊断块预算。编辑失败时,失败条目列表和候选锚点的上下文各按紧凑 JSON
|
|
190
|
+
参数拒绝报告序列化为 JSON 后不超过诊断块预算。编辑失败时,失败条目列表和候选锚点的上下文各按紧凑 JSON 计入一个诊断块,只省略完整条目或整行,并给出省略数量;replace 未匹配的规则列表和缺失路径列表同样如此。
|
|
185
191
|
|
|
186
192
|
模型容量未知或非法时,默认上限为 read 行 64 KiB、grep 载荷 50 KiB、每个诊断块 16 KiB、每个自由文本字段 4 KiB、每条 grep 预览 500 个 UTF-16 单元。显式设置 `read.maxKiB` 只覆盖 read 上限。每次执行使用开始时取得的预算快照。
|
|
187
193
|
|
|
188
|
-
Read 因默认行数或字节预算截断窗口时会报告 `nextOffset`;只有调用方指定的 `limit` 生效时不额外报告 `nextOffset`。首行放不下时报告 `lineTooLong
|
|
194
|
+
Read 因默认行数或字节预算截断窗口时会报告 `nextOffset`;只有调用方指定的 `limit` 生效时不额外报告 `nextOffset`。首行放不下时报告 `lineTooLong`,其值为字节上限。传 `anchors: false` 时,`offset` 超过最后一行会以 `OFFSET_PAST_END` 失败,并给出文件的 `totalLines`;从第一行读空文件返回空文本。Grep 分别报告载荷和行预览的截断,非法 UTF-8 的普通预览不带编辑锚点。
|
|
189
195
|
|
|
190
196
|
grep 载荷被截断时,只有去掉上下文后能在相同字节预算内多显示至少一条匹配行,报告才提示用 `context: 0` 重试;否则提示缩小搜索范围。依据部分预览重写前需检查完整行:`invalidUtf8` 列出的路径使用 Bash,有效 UTF-8 使用 `read`。
|
|
191
197
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"type": "module",
|
|
5
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",
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
"main": "src/index.ts",
|
|
15
15
|
"files": [
|
|
16
16
|
"src",
|
|
17
|
+
"!src/**/*.test.ts",
|
|
18
|
+
"!src/**/*.testing.ts",
|
|
19
|
+
"!src/integration",
|
|
20
|
+
"!src/testing",
|
|
21
|
+
"!src/core/pict-matrix.tsv",
|
|
17
22
|
"README.md",
|
|
18
23
|
"README.zh-CN.md",
|
|
19
24
|
"LICENSE",
|
|
@@ -33,6 +38,7 @@
|
|
|
33
38
|
"@earendil-works/pi-schema": "1.5.0",
|
|
34
39
|
"@eslint-community/regexpp": "4.12.2",
|
|
35
40
|
"@vscode/ripgrep": "1.18.0",
|
|
41
|
+
"diff": "8.0.4",
|
|
36
42
|
"jiti": "2.7.0"
|
|
37
43
|
},
|
|
38
44
|
"peerDependencies": {
|
|
@@ -45,6 +51,7 @@
|
|
|
45
51
|
"@earendil-works/pi-ai": "1.5.0",
|
|
46
52
|
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
47
53
|
"@earendil-works/pi-tui": "1.5.0",
|
|
54
|
+
"fast-check": "4.10.3",
|
|
48
55
|
"typebox": "1.3.27",
|
|
49
56
|
"typescript": "^7.0.2"
|
|
50
57
|
},
|
package/src/core/AGENTS.md
CHANGED
|
@@ -4,7 +4,7 @@ Internal pure engine: no Pi imports and no public API. It trusts input already f
|
|
|
4
4
|
|
|
5
5
|
## Modules
|
|
6
6
|
|
|
7
|
-
- `hash.ts` computes position-dependent line checksums (line number + content → `LINE#HASH`). `lines.ts` handles splitting, line
|
|
7
|
+
- `hash.ts` computes position-dependent line checksums (line number + content → `LINE#HASH`). `lines.ts` handles splitting, the separator for new line boundaries, 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
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.
|
|
@@ -15,5 +15,7 @@ Internal pure engine: no Pi imports and no public API. It trusts input already f
|
|
|
15
15
|
|
|
16
16
|
## Constraints
|
|
17
17
|
|
|
18
|
+
- `text.ts` classifies only Node's confirmed malformed UTF-8 error as `UNSUPPORTED_ENCODING` and preserves other decoder failures and their causes. Streaming validity checks (`src/pi/text-stream.ts`) catch only `Utf8DecodingError`.
|
|
19
|
+
- In `edit`, an empty body line is a real logical line. A trailing empty line that needs a terminator to be preserved gets one, except a BOM-only single line. A non-empty last line keeps its original final-newline state.
|
|
18
20
|
- 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
21
|
- 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.ts
CHANGED
|
@@ -31,12 +31,12 @@
|
|
|
31
31
|
|
|
32
32
|
import { computeLineHash } from "./hash.ts";
|
|
33
33
|
import {
|
|
34
|
-
|
|
34
|
+
newLineSeparator,
|
|
35
35
|
hasFinalNewline,
|
|
36
|
+
indexSourceLines,
|
|
36
37
|
joinTextFragments,
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
splitLines,
|
|
38
|
+
restoreLineEndings,
|
|
39
|
+
type TextFragment,
|
|
40
40
|
} from "./lines.ts";
|
|
41
41
|
import type { Anchor, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
|
|
42
42
|
import { HashlineError } from "./errors.ts";
|
|
@@ -61,7 +61,7 @@ interface SpanOp {
|
|
|
61
61
|
* hash computed for that line, so it verifies on retry.
|
|
62
62
|
*/
|
|
63
63
|
function verifyAnchor(
|
|
64
|
-
lines:
|
|
64
|
+
lines: ReturnType<typeof indexSourceLines>,
|
|
65
65
|
cited: Anchor,
|
|
66
66
|
which: AnchorFailure["which"],
|
|
67
67
|
opIndex: number,
|
|
@@ -70,14 +70,16 @@ function verifyAnchor(
|
|
|
70
70
|
radius: number,
|
|
71
71
|
): AnchorFailure | null {
|
|
72
72
|
const { line, hash } = cited;
|
|
73
|
-
if (line <= lines.length && computeLineHash(line, lines
|
|
73
|
+
if (line <= lines.length && computeLineHash(line, lines.content(line - 1), hashLen) === hash)
|
|
74
|
+
return null;
|
|
74
75
|
|
|
75
76
|
const candidates: { line: number; hash: string }[] = [];
|
|
76
77
|
const scan = (start: number, end: number) => {
|
|
77
78
|
for (let c = start; c <= end; c++) {
|
|
78
79
|
if (c === line) continue;
|
|
79
|
-
|
|
80
|
-
|
|
80
|
+
const content = lines.content(c - 1);
|
|
81
|
+
if (computeLineHash(line, content, hashLen) === hash) {
|
|
82
|
+
candidates.push({ line: c, hash: computeLineHash(c, content, hashLen) });
|
|
81
83
|
}
|
|
82
84
|
}
|
|
83
85
|
};
|
|
@@ -104,53 +106,44 @@ function verifyAnchor(
|
|
|
104
106
|
return { opIndex, which, op, cited, recovery };
|
|
105
107
|
}
|
|
106
108
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
/** Verify an Edit against the snapshot and plan its mutation span. */
|
|
112
|
-
function translateEdit(
|
|
113
|
-
edit: Edit,
|
|
114
|
-
opIndex: number,
|
|
115
|
-
lines: readonly string[],
|
|
109
|
+
/** Verify each cited endpoint in input order, including the end of a failed range. */
|
|
110
|
+
function verifyEditAnchors(
|
|
111
|
+
edits: readonly Edit[],
|
|
112
|
+
lines: ReturnType<typeof indexSourceLines>,
|
|
116
113
|
hashLen: number,
|
|
117
114
|
radius: number,
|
|
118
|
-
):
|
|
119
|
-
const
|
|
120
|
-
|
|
115
|
+
): AnchorFailure[] {
|
|
116
|
+
const failures: AnchorFailure[] = [];
|
|
117
|
+
for (const [opIndex, edit] of edits.entries()) {
|
|
118
|
+
if (!("anchor" in edit)) continue;
|
|
119
|
+
const anchor = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
|
|
120
|
+
if (anchor) failures.push(anchor);
|
|
121
|
+
if (!("end" in edit) || !edit.end) continue;
|
|
122
|
+
const end = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
|
|
123
|
+
if (end) failures.push(end);
|
|
124
|
+
}
|
|
125
|
+
return failures;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Convert verified line addresses to half-open spans. */
|
|
129
|
+
function planSpan(edit: Edit, lineCount: number): SpanOp {
|
|
121
130
|
switch (edit.op) {
|
|
122
131
|
case "replace":
|
|
123
|
-
case "delete":
|
|
124
|
-
const failures: AnchorFailure[] = [];
|
|
125
|
-
const anchorF = verify(edit.anchor, "anchor");
|
|
126
|
-
if (anchorF) failures.push(anchorF);
|
|
127
|
-
let endLine = edit.anchor.line;
|
|
128
|
-
if (edit.end) {
|
|
129
|
-
const endF = verify(edit.end, "end");
|
|
130
|
-
if (endF) failures.push(endF);
|
|
131
|
-
endLine = edit.end.line;
|
|
132
|
-
}
|
|
133
|
-
if (failures.length > 0) return { ok: false, anchorFailures: failures };
|
|
132
|
+
case "delete":
|
|
134
133
|
return {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
hi: endLine,
|
|
139
|
-
newLines: edit.op === "replace" ? edit.body : [],
|
|
140
|
-
},
|
|
134
|
+
lo: edit.anchor.line - 1,
|
|
135
|
+
hi: (edit.end ?? edit.anchor).line,
|
|
136
|
+
newLines: edit.op === "replace" ? edit.body : [],
|
|
141
137
|
};
|
|
142
|
-
}
|
|
143
138
|
case "insert_after":
|
|
144
139
|
case "insert_before": {
|
|
145
|
-
const failure = verify(edit.anchor, "anchor");
|
|
146
|
-
if (failure) return { ok: false, anchorFailures: [failure] };
|
|
147
140
|
const line = edit.anchor.line - (edit.op === "insert_before" ? 1 : 0);
|
|
148
|
-
return {
|
|
141
|
+
return { lo: line, hi: line, newLines: edit.body };
|
|
149
142
|
}
|
|
150
143
|
case "append":
|
|
151
|
-
return {
|
|
144
|
+
return { lo: lineCount, hi: lineCount, newLines: edit.body };
|
|
152
145
|
case "prepend":
|
|
153
|
-
return {
|
|
146
|
+
return { lo: 0, hi: 0, newLines: edit.body };
|
|
154
147
|
}
|
|
155
148
|
}
|
|
156
149
|
|
|
@@ -170,38 +163,24 @@ export function applyEdits(
|
|
|
170
163
|
hashLen: number,
|
|
171
164
|
shiftRadius: number,
|
|
172
165
|
): ApplyResult {
|
|
173
|
-
const lines =
|
|
174
|
-
const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
175
|
-
const ending = detectLineEnding(text);
|
|
176
|
-
|
|
177
|
-
const ops: (SpanOp & { readonly opIndex: number })[] = [];
|
|
178
|
-
const anchorFailures: AnchorFailure[] = [];
|
|
179
|
-
|
|
180
|
-
for (let i = 0; i < edits.length; i++) {
|
|
181
|
-
const t = translateEdit(edits[i], i, lines, hashLen, shiftRadius);
|
|
182
|
-
if (t.ok) {
|
|
183
|
-
ops.push({ ...t.op, opIndex: i });
|
|
184
|
-
} else {
|
|
185
|
-
anchorFailures.push(...t.anchorFailures);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
166
|
+
const lines = indexSourceLines(text);
|
|
188
167
|
|
|
189
|
-
//
|
|
190
|
-
|
|
191
|
-
if (anchorFailures.length > 0) {
|
|
192
|
-
return { ok: false, failures: anchorFailures };
|
|
193
|
-
}
|
|
168
|
+
// Report anchor failures before checking the resulting spans for conflicts.
|
|
169
|
+
const anchorFailures = verifyEditAnchors(edits, lines, hashLen, shiftRadius);
|
|
170
|
+
if (anchorFailures.length > 0) return { ok: false, failures: anchorFailures };
|
|
194
171
|
|
|
195
|
-
const sorted =
|
|
172
|
+
const sorted = edits
|
|
173
|
+
.map((edit, opIndex) => ({ ...planSpan(edit, lines.length), opIndex }))
|
|
174
|
+
.sort((a, b) => a.lo - b.lo || a.hi - b.hi);
|
|
196
175
|
const conflict = findSortedRangeConflict(
|
|
197
176
|
sorted.map((op) => [op.lo, op.hi]),
|
|
198
|
-
|
|
177
|
+
"allow-insertion-before-range",
|
|
199
178
|
);
|
|
200
179
|
if (conflict !== undefined) {
|
|
201
180
|
const current = sorted[conflict];
|
|
202
181
|
const previous = sorted[conflict - 1];
|
|
203
|
-
|
|
204
|
-
|
|
182
|
+
// At an empty span, only another insertion at the same gap can conflict.
|
|
183
|
+
const repeatedInsertion = previous.lo === previous.hi;
|
|
205
184
|
throw new HashlineError(
|
|
206
185
|
"OVERLAPPING_EDITS",
|
|
207
186
|
repeatedInsertion ? "Two steps insert at one position." : "Two steps overlap.",
|
|
@@ -217,61 +196,75 @@ export function applyEdits(
|
|
|
217
196
|
);
|
|
218
197
|
}
|
|
219
198
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
//
|
|
231
|
-
const
|
|
232
|
-
let
|
|
199
|
+
const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
200
|
+
const separator = newLineSeparator(text);
|
|
201
|
+
const contentStart = (line: number) => (line === 0 ? bom.length : lines.start(line));
|
|
202
|
+
/** The source gap after a line, or the separator after an unterminated last line. */
|
|
203
|
+
const gapAfter = (line: number): TextFragment => {
|
|
204
|
+
const start = lines.end(line);
|
|
205
|
+
const end = lines.start(line + 1);
|
|
206
|
+
return start !== end ? [start, end] : separator;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
// The previous span's trailing gap connects to the next span, unless it ends the file.
|
|
210
|
+
const parts: TextFragment[] = [[0, bom.length]];
|
|
211
|
+
let lineCount = 0;
|
|
212
|
+
let lastLineEmpty = false;
|
|
213
|
+
let trailingGap: TextFragment = "";
|
|
214
|
+
const appendSpan = (
|
|
215
|
+
content: TextFragment,
|
|
216
|
+
count: number,
|
|
217
|
+
endsEmpty: boolean,
|
|
218
|
+
gap: TextFragment,
|
|
219
|
+
) => {
|
|
220
|
+
parts.push(trailingGap, content);
|
|
221
|
+
lineCount += count;
|
|
222
|
+
lastLineEmpty = endsEmpty;
|
|
223
|
+
trailingGap = gap;
|
|
224
|
+
};
|
|
225
|
+
|
|
233
226
|
const appendSource = (start: number, end: number) => {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
227
|
+
if (start === end) return;
|
|
228
|
+
const last = end - 1;
|
|
229
|
+
const sourceStart = contentStart(start);
|
|
230
|
+
const contentEnd = lines.end(last);
|
|
231
|
+
appendSpan(
|
|
232
|
+
[sourceStart, contentEnd],
|
|
233
|
+
end - start,
|
|
234
|
+
contentStart(last) === contentEnd,
|
|
235
|
+
gapAfter(last),
|
|
236
|
+
);
|
|
242
237
|
};
|
|
238
|
+
|
|
239
|
+
let cursor = 0;
|
|
243
240
|
for (const op of sorted) {
|
|
244
241
|
appendSource(cursor, op.lo);
|
|
245
|
-
// The trailing gap is outside the logical replacement, just as in substring replacement.
|
|
246
|
-
const removedSeparators = separators?.slice(op.lo, Math.max(op.lo, op.hi - 1)) ?? [];
|
|
247
|
-
for (let i = 0; i < op.newLines.length; i++) {
|
|
248
|
-
const content = op.newLines[i];
|
|
249
|
-
result.push({
|
|
250
|
-
// Only a replacement of the original first line can carry its copied BOM.
|
|
251
|
-
content:
|
|
252
|
-
bom && op.lo === 0 && op.hi > 0 && i === 0 && content.startsWith(bom)
|
|
253
|
-
? content.slice(1)
|
|
254
|
-
: content,
|
|
255
|
-
separator:
|
|
256
|
-
i === op.newLines.length - 1 && op.hi > op.lo
|
|
257
|
-
? (separators?.[op.hi - 1] ?? "")
|
|
258
|
-
: replacementSeparator(removedSeparators, i, separator),
|
|
259
|
-
});
|
|
260
|
-
}
|
|
261
242
|
cursor = op.hi;
|
|
243
|
+
if (op.newLines.length === 0) continue;
|
|
244
|
+
|
|
245
|
+
let logical = op.newLines.join("\n");
|
|
246
|
+
// Only replacement of the original first line can carry a copied file BOM.
|
|
247
|
+
if (bom && op.lo === 0 && op.hi > 0 && logical.startsWith(bom)) logical = logical.slice(1);
|
|
248
|
+
|
|
249
|
+
// Borrow only the internal gaps the body can use. Keep the replaced range's
|
|
250
|
+
// trailing gap at its right boundary.
|
|
251
|
+
const usedGaps = Math.min(op.hi - op.lo, op.newLines.length) - 1;
|
|
252
|
+
const oldInternal =
|
|
253
|
+
usedGaps > 0 && separator === "\r\n"
|
|
254
|
+
? text.slice(lines.end(op.lo), lines.start(op.lo + usedGaps))
|
|
255
|
+
: "";
|
|
256
|
+
appendSpan(
|
|
257
|
+
op.newLines.length > 1 ? restoreLineEndings(logical, oldInternal, separator) : logical,
|
|
258
|
+
op.newLines.length,
|
|
259
|
+
logical === "" || logical.endsWith("\n"),
|
|
260
|
+
op.hi > op.lo ? gapAfter(op.hi - 1) : separator,
|
|
261
|
+
);
|
|
262
262
|
}
|
|
263
263
|
appendSource(cursor, lines.length);
|
|
264
|
-
|
|
265
|
-
// A
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
joinTextFragments(
|
|
271
|
-
result.flatMap(({ content, separator: current }, i) => [
|
|
272
|
-
content,
|
|
273
|
-
i < result.length - 1 || finalNewline ? current || separator : "",
|
|
274
|
-
]),
|
|
275
|
-
);
|
|
276
|
-
return { ok: true, text: newText };
|
|
264
|
+
|
|
265
|
+
// A final blank line needs a terminator unless the BOM alone represents it.
|
|
266
|
+
if (hasFinalNewline(text) || (lastLineEmpty && (lineCount > 1 || !bom))) {
|
|
267
|
+
parts.push(trailingGap);
|
|
268
|
+
}
|
|
269
|
+
return { ok: true, ...joinTextFragments(text, parts) };
|
|
277
270
|
}
|
|
@@ -85,9 +85,8 @@ export const total = (ranges: Ranges): number =>
|
|
|
85
85
|
export const contains = (ranges: Ranges, point: number): boolean =>
|
|
86
86
|
ranges.some(([low, high]) => low <= point && point <= high);
|
|
87
87
|
|
|
88
|
-
/** Full-string membership,
|
|
89
|
-
const membership = (source: string, flags: string): RegExp =>
|
|
90
|
-
new RegExp(`^(?:${source})(?![\\s\\S])`, flags);
|
|
88
|
+
/** Full-string membership; without the m flag, JavaScript's $ matches only at the end of input. */
|
|
89
|
+
const membership = (source: string, flags: string): RegExp => new RegExp(`^(?:${source})$`, flags);
|
|
91
90
|
|
|
92
91
|
/** The UTF-16 units a validated expression matches; flags contain only i or s. */
|
|
93
92
|
export function nativeCharacterRanges(source: string, flags: string): Ranges {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Type, type Static } from "typebox";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Equal raw UTF-16 slices in the source and target, ordered and non-overlapping on both sides.
|
|
5
|
+
* Gaps between spans have unknown provenance.
|
|
6
|
+
*/
|
|
7
|
+
export const COPIED_SPAN_SCHEMA = Type.Object(
|
|
8
|
+
{
|
|
9
|
+
sourceStart: Type.Integer({ minimum: 0 }),
|
|
10
|
+
targetStart: Type.Integer({ minimum: 0 }),
|
|
11
|
+
length: Type.Integer({ minimum: 1 }),
|
|
12
|
+
},
|
|
13
|
+
{ additionalProperties: false },
|
|
14
|
+
);
|
|
15
|
+
export type CopiedSpan = Readonly<Static<typeof COPIED_SPAN_SCHEMA>>;
|