@criogaid/pi-hashline-edit 0.1.2 → 0.2.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 +67 -21
- package/package.json +1 -1
- package/src/core/apply.test.ts +85 -8
- package/src/core/apply.ts +99 -79
- package/src/core/ranges.test.ts +28 -0
- package/src/core/ranges.ts +25 -0
- package/src/core/text.ts +5 -0
- package/src/core/types.ts +37 -20
- package/src/integration/grep-rg.test.ts +76 -1
- package/src/pi/action-fusion.test.ts +1 -1
- package/src/pi/action-fusion.ts +9 -21
- package/src/pi/anchor-format.test.ts +30 -0
- package/src/pi/anchor-format.ts +28 -0
- package/src/pi/config.test.ts +6 -9
- package/src/pi/config.ts +4 -4
- package/src/pi/edit-tool.ts +90 -99
- package/src/pi/execute.test.ts +240 -14
- package/src/pi/failure-context.test.ts +99 -62
- package/src/pi/failure-context.ts +67 -64
- package/src/pi/failure-path.test.ts +3 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/grep-tool.ts +75 -48
- package/src/pi/grep.test.ts +67 -3
- package/src/pi/mutation-result.ts +46 -9
- package/src/pi/read-tool.ts +7 -10
- package/src/pi/registration.test.ts +15 -2
- package/src/pi/render.test.ts +24 -0
- package/src/pi/render.ts +18 -4
- package/src/pi/replace-tool.ts +134 -130
- package/src/pi/replace.test.ts +118 -1
- package/src/pi/result-safety.test.ts +241 -8
- package/src/pi/rg-line-filter.test.ts +7 -1
- package/src/pi/rg-line-filter.ts +9 -11
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/state.ts +2 -3
- package/src/pi/write-tool.ts +10 -44
- package/src/pi/write.test.ts +25 -36
package/README.md
CHANGED
|
@@ -8,8 +8,8 @@ Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk trans
|
|
|
8
8
|
|
|
9
9
|
- **Search → edit:** `read` and `grep` return the same `LINE#HASH` anchors, so search results can feed directly into edits.
|
|
10
10
|
- **Batch and chain edits:** submit structured JSON operations together, then use the returned fresh anchors for the next change.
|
|
11
|
-
- **Recover from stale anchors:** rejected edits
|
|
12
|
-
- **Edit → test:**
|
|
11
|
+
- **Recover from stale anchors:** rejected edits show a unique checksum-matching candidate's line, or neighborhoods around ambiguous candidates for comparison. With no candidate, they ask the model to re-read the file. Recovery never applies automatically.
|
|
12
|
+
- **Edit → test:** Action Fusion lets a mutation include an optional follow-up command, with separate file and command outcomes and separate TUI cards.
|
|
13
13
|
|
|
14
14
|
[Quick start](#quick-start) · [Tools](#tools) · [Configuration](#configuration) · [Action Fusion](#action-fusion) · [Safety and design](#safety-and-design)
|
|
15
15
|
|
|
@@ -48,11 +48,13 @@ To change the return value, copy the second line's anchor into `edit` and supply
|
|
|
48
48
|
The result includes a diff and the updated anchor:
|
|
49
49
|
|
|
50
50
|
```text
|
|
51
|
-
Updated anchors
|
|
52
|
-
2#V8AT
|
|
51
|
+
Updated anchors:
|
|
52
|
+
2#V8AT
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
Use returned anchors for subsequent edits. Content-mode `grep` provides the same references, grouped by file. Always copy actual tool output; the examples use the default four-character hash.
|
|
55
|
+
Use returned anchors for changed lines in subsequent edits. Previously observed anchors remain usable when their line number, full content, and hash-length configuration are unchanged. Content-mode `grep` provides the same references, grouped by file. Always copy actual tool output; the examples use the default four-character hash.
|
|
56
|
+
|
|
57
|
+
Successful `edit` and `replace` results omit candidate rows whose full content at the same line number is unchanged, then return compact `LINE#HASH` tokens by default. `edit` retains complete content for a deletion successor unless the batch also supplies that row; `replace` retains it for the first surviving line after a pure deletion. Anchor reports have a 16 KiB byte limit, including heading/omission notice, with no fixed entry-count limit. Neither tool reports every shifted line in the remaining file; read shifted positions when needed and no fresh anchor was returned. `write` returns no anchors. Explicit `read`/`grep` results and edit failure context continue to include the requested or diagnostic rows.
|
|
56
58
|
|
|
57
59
|
## Tools
|
|
58
60
|
|
|
@@ -79,6 +81,18 @@ All tools accept relative or absolute paths and expand a leading `~`. Mutation t
|
|
|
79
81
|
|
|
80
82
|
All operations in a batch use the same snapshot. Validation failure rejects the whole batch. Conflicting fields and overlapping operations are rejected; some touching operations also conflict and need separate calls with fresh anchors. For insertion, **do not repeat the anchor line in `body`**. `edit` uses structured operations, not `oldText`/`newText` pairs.
|
|
81
83
|
|
|
84
|
+
Rejected batches report each supplied anchor's status from that validation snapshot: `matched`, `mismatched`, or `not_checked` when body validation stopped the batch before hashing. Entries identify the zero-based operation index, `anchor` or `end`, and the cited token. The bounded list reports omitted entries explicitly. These statuses do not establish range/overlap validity, semantic intent, publication, command success, or validity on a later retry.
|
|
85
|
+
|
|
86
|
+
Recovery first searches within `shiftRadius` of the cited line. If that search finds no candidates, it searches the rest of the file and collects all checksum matches before deciding whether the result is unique or ambiguous. Existing local candidates take priority; distant matches are not added when local candidates exist. `shiftRadius: 0` disables both searches. Candidate matching holds the original line number fixed when hashing current content; returned anchors use each candidate's actual line number.
|
|
87
|
+
|
|
88
|
+
Candidate diagnostics identify the search as `Search: local` or `Search: full file`. Local results explicitly state that matches outside the window were not checked: a unique local candidate does not establish uniqueness across the file. The cited line and returned candidate anchor show the old and current positions.
|
|
89
|
+
|
|
90
|
+
A unique recovery candidate returns its new anchor and complete line content, without a neighborhood. Content is shown once per line and is limited to 4 KiB per candidate row; oversized content is omitted in full with a prompt to use `read` or `grep`.
|
|
91
|
+
|
|
92
|
+
Ambiguous failures list up to eight candidate anchors and include a bounded ±3-line neighborhood around each listed candidate from the same snapshot. Windows are clipped to file boundaries, merged, and emitted in ascending line order within byte budgets. Neighboring rows are observations, not recommended replacement targets. Candidate content already present in a neighborhood is not repeated in failure details. Inspect the code to choose the correct anchor and operation, then resubmit. No edit or retry is performed automatically, and every submitted anchor is verified again.
|
|
93
|
+
|
|
94
|
+
When no candidate is found, diagnostics ask the caller to use `read` to inspect the current file before retrying and include no context rows for that failure. Input-anchor checks still report the cited tokens and their validation status.
|
|
95
|
+
|
|
82
96
|
### Bulk replacement
|
|
83
97
|
|
|
84
98
|
For a rename across a file:
|
|
@@ -93,6 +107,20 @@ Literal mode inserts replacement text verbatim. Set `regex: true` for JavaScript
|
|
|
93
107
|
{ "path": "src/foo.ts", "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }
|
|
94
108
|
```
|
|
95
109
|
|
|
110
|
+
To apply several rules against the same original content:
|
|
111
|
+
|
|
112
|
+
```json
|
|
113
|
+
{
|
|
114
|
+
"path": "src/foo.ts",
|
|
115
|
+
"replacements": [
|
|
116
|
+
{ "find": "foo", "replace": "bar" },
|
|
117
|
+
{ "find": "bar", "replace": "baz" }
|
|
118
|
+
]
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Original `foo bar` becomes `bar baz`; inserted text is not searched again. All rules must succeed before one file commit. `then_run`, when supplied, runs once after the entire batch succeeds.
|
|
123
|
+
|
|
96
124
|
<details>
|
|
97
125
|
<summary><strong>Full read, grep, replace, and write parameter reference</strong></summary>
|
|
98
126
|
|
|
@@ -108,7 +136,7 @@ Required: `path`. Optional: 1-based `offset` (default 1) and `limit` (default 20
|
|
|
108
136
|
| `path` | Current directory | One path or an array of search roots. |
|
|
109
137
|
| `matchMode` | `"any"` | OR across patterns; `"all"` requires every pattern on the same physical line, at most 16 patterns. |
|
|
110
138
|
| `excludePattern` | None | String or array; remove lines matching any exclusion. |
|
|
111
|
-
| `literal` | Automatic | `true`: literal strings. `false`: strict regex. Automatic mode detects regex metacharacters
|
|
139
|
+
| `literal` | Automatic | `true`: literal strings. `false`: strict regex. Automatic mode detects regex metacharacters; parse failures fall back to literal text only for one inclusion pattern without exclusions. Invalid compound queries fail with guidance to fix the regex or explicitly set `literal: true`. |
|
|
112
140
|
| `ignoreCase` | Smart-case | Explicit `true`/`false` overrides case handling; the query-level decision also applies to exclusions. |
|
|
113
141
|
| `wordMatch` | `false` | Whole-word matches. |
|
|
114
142
|
| `glob` | None | One glob or an ordered array; prefix exclusions with `!`. |
|
|
@@ -124,15 +152,21 @@ Context is rebuilt from surviving matches. Multiline filtering, counting, and li
|
|
|
124
152
|
|
|
125
153
|
All inclusion/exclusion matching uses bundled ripgrep, independent of system `rg` or `PATH`. Searches are CRLF-aware, include hidden files while respecting ignore rules, and pass `--no-config`. The default engine is Rust regex; PCRE2 never silently falls back to another engine or literal matching.
|
|
126
154
|
|
|
155
|
+
Search diagnostics are preserved even when a result limit stops ripgrep. Readable, confirmed matches remain available with a `Search incomplete` notice and `details.incomplete: true`; counts then cover only confirmed matches. If no results can be returned, the tool reports an error rather than claiming there are no matches. Exclusion-scan failures still reject the query, because incomplete exclusions could admit incorrect results. Search diagnostics have a separate 4 KiB display budget.
|
|
156
|
+
|
|
157
|
+
Long lines show a labeled partial preview of up to 500 UTF-16 units around a ripgrep match; context-only lines show their beginning. Labels report 1-based UTF-16 column ranges, and slicing preserves surrogate pairs. The anchor hashes the entire current line, not the preview; use `read` before reconstructing a line from its content.
|
|
158
|
+
|
|
127
159
|
### Replace
|
|
128
160
|
|
|
129
|
-
Required: `path`, `find`, `replace`.
|
|
161
|
+
Required: `path` and either top-level `find` / `replace`, or a non-empty `replacements` array. These forms are mutually exclusive: batch calls cannot include top-level `find`, `replace`, `regex`, `flags`, or `maxMatches`. Each rule requires `find` and `replace`, with these optional fields:
|
|
130
162
|
|
|
131
163
|
- `regex`: defaults to `false`; regex mode supports capture groups, the full match, and prefix/suffix substitutions.
|
|
132
164
|
- `flags`: applies in both modes; `g` is always added. Supported flags: `g i m s u y d`.
|
|
133
|
-
- `maxMatches`: defaults to 2000; rejects excess matches before writing. Raise it for intentional bulk changes. It does not bound regex execution time or result size.
|
|
165
|
+
- `maxMatches`: defaults to 2000 per rule and must be finite and positive; rejects excess matches before writing. Raise it for intentional bulk changes. It does not bound regex execution time or result size.
|
|
134
166
|
|
|
135
|
-
Zero matches
|
|
167
|
+
Zero matches in any rule, an invalid rule, or overlapping match ranges rejects the whole call without writing. Adjacent ranges are allowed. Zero-length matches conflict at the same position or at the start/interior of another match; a zero-length match at another match's end is allowed unless it conflicts with a following match. Error rule indices and string offsets are zero-based (offsets count UTF-16 code units).
|
|
168
|
+
|
|
169
|
+
Regex captures and prefix/suffix substitutions always refer to the original snapshot.
|
|
136
170
|
|
|
137
171
|
### Write
|
|
138
172
|
|
|
@@ -142,8 +176,14 @@ Required: `path`, `content`. By default, create missing files and overwrite exis
|
|
|
142
176
|
- `mode: "overwrite"`: require an existing target.
|
|
143
177
|
- `expectedRevision`: strictly check the current file's SHA-256; cannot be combined with create mode.
|
|
144
178
|
|
|
179
|
+
Write results report the write outcome without returning line anchors. Use `read` or content-mode `grep` to obtain anchors for a later `edit`.
|
|
180
|
+
|
|
181
|
+
Normal write result text omits the revision. Programmatic callers can read `details.publishedRevision`; text-only callers needing `expectedRevision` must obtain a SHA-256 of the file bytes separately. Revision checks and structured revision fields remain active.
|
|
182
|
+
|
|
145
183
|
With Action Fusion enabled, `edit`, `replace`, and `write` also accept `then_run`.
|
|
146
184
|
|
|
185
|
+
All three mutation tools treat identical final content as a successful no-op: report `no net change`, leave the existing file untouched, and return `publication: "NOT_PUBLISHED"`. A requested `then_run` still runs after freshness checks. Input, anchor, match, target-type, mode, revision, and cancellation checks still apply; zero matches, stale anchors/revisions, and an existing target in create mode remain errors. Creating a missing empty file is a publication, not a no-op.
|
|
186
|
+
|
|
147
187
|
</details>
|
|
148
188
|
|
|
149
189
|
## Configuration
|
|
@@ -154,7 +194,7 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
|
|
|
154
194
|
{
|
|
155
195
|
"hashlineEdit": {
|
|
156
196
|
"enabled": true,
|
|
157
|
-
"actionFusion":
|
|
197
|
+
"actionFusion": true,
|
|
158
198
|
"hashLen": 4,
|
|
159
199
|
"shiftRadius": 15
|
|
160
200
|
}
|
|
@@ -164,15 +204,15 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
|
|
|
164
204
|
| Setting | Default | Meaning |
|
|
165
205
|
| --- | --- | --- |
|
|
166
206
|
| `enabled` | `true` | Enable all five tools as one unit. Set `false` to restore built-in tools. |
|
|
167
|
-
| `actionFusion` | `
|
|
207
|
+
| `actionFusion` | `true` | Expose `then_run` on mutation tools. Set `false` to disable command support. |
|
|
168
208
|
| `hashLen` | `4` | Integer checksum length, 2–8 characters. |
|
|
169
|
-
| `shiftRadius` | `15` | Integer recovery-search radius, 0–100 lines; `0` disables
|
|
209
|
+
| `shiftRadius` | `15` | Integer first-pass recovery-search radius, 0–100 lines. With no local candidates, recovery searches the rest of the file; `0` disables both searches. |
|
|
170
210
|
|
|
171
211
|
The project's `hashlineEdit` object replaces the global object as a whole; missing or invalid fields use defaults. Reload Pi after changes.
|
|
172
212
|
|
|
173
213
|
## Action Fusion
|
|
174
214
|
|
|
175
|
-
|
|
215
|
+
Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdit` and reload Pi to disable it; an existing explicit `false` remains effective. Commands run only when a call supplies `then_run`:
|
|
176
216
|
|
|
177
217
|
```json
|
|
178
218
|
{
|
|
@@ -193,7 +233,7 @@ Fusion serializes each mutation/command sequence for its target and checks the p
|
|
|
193
233
|
|
|
194
234
|
- **Anchors are checksums, not identities.** Each hash combines the 1-based line number and content. Short hashes can collide and do not prove the model observed a line.
|
|
195
235
|
- **Validation is local to supplied anchors.** Unrelated in-place changes leave stable anchors usable. A range verifies its supplied start/end anchors, not every interior line.
|
|
196
|
-
- **Line shifts change anchors.** Insertions/deletions can invalidate later references. Recovery searches within `shiftRadius
|
|
236
|
+
- **Line shifts change anchors.** Insertions/deletions can invalidate later references. Recovery searches within `shiftRadius`, then the rest of the file if no local candidates match. Unique candidates include bounded line content; ambiguous candidates include neighborhoods for comparison. Use `read` when no candidate is found or needed content is omitted. Retries verify again, without fuzzy matching or automatic relocation.
|
|
197
237
|
- **Edits preserve text representation.** `edit` preserves existing line endings, untouched separators, and the absence of a final newline. `edit`/`replace` reject invalid UTF-8 source text; all mutations reject NUL and output that cannot be encoded losslessly as UTF-8.
|
|
198
238
|
- **Fresh anchors depend on the final observation.** After `then_run`, anchors are shown only for `unchanged` freshness. Without a command, observed and published revisions must agree. Later edits still verify anchors.
|
|
199
239
|
- **Local queues are not cross-process transactions.** Revision checks bind mutations to the bytes read, but an external writer can still race a check and publication. There is no strict workspace jail or multi-file transaction.
|
|
@@ -205,6 +245,8 @@ Fusion serializes each mutation/command sequence for its target and checks the p
|
|
|
205
245
|
|
|
206
246
|
`read` computes line hashes only for its requested window; `grep` hashes selected matches/context. Both still read and decode whole files. Mutation revision checks cover actual bytes.
|
|
207
247
|
|
|
248
|
+
Line boundaries are LF or CRLF; a standalone CR remains line content. Anchored rows display standalone CR as `␍` (U+240D), while hashes use the original content. Edit/replace diff previews also show CR as `␍`, including CR in CRLF endings; their unified patches retain the original characters and line endings. The marker is a display aid, not replacement text.
|
|
249
|
+
|
|
208
250
|
An existing UTF-8 BOM stays at byte zero through first-line replacement/deletion or insertion; deleting all content leaves the BOM. First-line hashes include it. A copied leading BOM in the first replacement/insertion line denotes the existing header; interior `U+FEFF` remains content. BOM-only files retain one anchored line. `replace` can explicitly match the BOM; `write` uses supplied content.
|
|
209
251
|
|
|
210
252
|
### Output budgets
|
|
@@ -213,18 +255,22 @@ These limits bound model context, not file size. Omission notices direct the cal
|
|
|
213
255
|
|
|
214
256
|
| Output | Limit |
|
|
215
257
|
| --- | --- |
|
|
216
|
-
| `read` | Default 2000 rows, overridable with `limit`; 256 KiB of anchored text. No partial anchor rows. |
|
|
217
|
-
| `grep` | Default 100 matching lines, overridable; 500
|
|
218
|
-
| `edit` / `replace` anchors |
|
|
219
|
-
|
|
|
220
|
-
|
|
|
258
|
+
| `read` | Default 2000 rows, overridable with `limit`; 256 KiB of anchored text. No partial anchor rows. An oversized single row directs the caller to inspect chunks with `bash` or make a known text change with `replace`; reducing `limit` cannot split a physical line. |
|
|
259
|
+
| `grep` | Default 100 matching lines, overridable; up to 500 UTF-16 units per partial line preview, plus labels and Pi's total output limits. Match previews use rg byte offsets; hashes use full content. Search error notices have a separate 4 KiB budget. |
|
|
260
|
+
| `edit` / `replace` anchors | 16 KiB including heading/omission notice, with no fixed entry-count limit. Compact tokens for changed positions; selected deletion successors retain complete content. Rows that do not fit are omitted in full; later rows that fit are still returned. |
|
|
261
|
+
| Anchor failure details | 16 KiB, with no fixed failure-count limit; unique candidates include complete rows up to 4 KiB, and ambiguous failures list up to eight candidates each. Unresolved anchors request a fresh read without context rows. |
|
|
262
|
+
| Input-anchor checks | Independent 16 KiB block, with no fixed entry-count limit. Truncation is reported explicitly; omitted entries are not implied matched. |
|
|
263
|
+
| Ambiguous-candidate neighborhoods | 16 KiB of complete anchored row text, lowest-line first, plus headings; no fixed row-count limit. Uses the same first eight candidates per failure as the detail lists. Each listed candidate row is limited to 4 KiB. Rows exceeding either limit are omitted in full; later rows that fit are still returned, with gaps reflected in the neighborhood headings. |
|
|
264
|
+
|
|
265
|
+
The diagnostic blocks have independent budgets; their combined output can exceed 16 KiB. Truncation notices identify exhausted budgets; context windows also report shown/omitted row counts. Limits apply to rendered diagnostics; core failure results retain all input-anchor checks.
|
|
221
266
|
|
|
222
267
|
### Publication
|
|
223
268
|
|
|
224
|
-
The shared commit layer prepares and syncs complete content in a sibling temporary directory. `edit`/`replace` bind publication to the revision of the bytes they read.
|
|
269
|
+
The shared commit layer validates the target and skips publication when the requested UTF-8 bytes have the current file's SHA-256. Otherwise, it prepares and syncs complete content in a sibling temporary directory. `edit`/`replace` bind this check and publication to the revision of the bytes they read.
|
|
225
270
|
|
|
226
271
|
| Case | Behavior |
|
|
227
272
|
| --- | --- |
|
|
273
|
+
| No-op | After validation, return existing revisions without creating a temporary file or replacing the target. |
|
|
228
274
|
| Create | Same-filesystem `link(temp, target)` refuses a target created by another writer during publication. |
|
|
229
275
|
| Overwrite | `rename(temp, target)` publishes the replacement; never delete the old target first. |
|
|
230
276
|
| Symlinks | Resolve the regular-file target for overwrite and preserve the link; reject dangling/unresolvable links. |
|
|
@@ -240,7 +286,7 @@ The shared commit layer prepares and syncs complete content in a sibling tempora
|
|
|
240
286
|
| `publication` | `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Fusion also reports it in `actionFusion.publication`. |
|
|
241
287
|
| `baseRevision` | SHA-256 of bytes read before mutation, when available. |
|
|
242
288
|
| `publishedRevision` | SHA-256 of intended published bytes; `revision` is its compatibility alias. |
|
|
243
|
-
| `observedRevision` | SHA-256 observed by the commit layer after publication. |
|
|
289
|
+
| `observedRevision` | SHA-256 observed by the commit layer after publication, or at the no-op check. |
|
|
244
290
|
| `actionFusion.command` | `not_requested`, `skipped`, `succeeded`, `failed`, `timeout`, or `cancelled`. |
|
|
245
291
|
| `actionFusion.freshness` | `unchanged`, `changed`, `missing`, or `unknown`, relative to the published revision. |
|
|
246
292
|
| `actionFusion.mutationCompleted` | Progress flag set after mutation execution and result generation succeed; publication alone is not mutation success. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.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",
|
package/src/core/apply.test.ts
CHANGED
|
@@ -157,11 +157,14 @@ test("conflict at the same insertion point rejected", () => {
|
|
|
157
157
|
if (!r.ok) assert.equal(r.failure.kind, "range");
|
|
158
158
|
});
|
|
159
159
|
|
|
160
|
-
test("
|
|
161
|
-
const text
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
160
|
+
test("byte-identical edits succeed without updated anchors after validation", () => {
|
|
161
|
+
for (const text of ["a\nb\n", "\uFEFFa\r\nb\n"]) {
|
|
162
|
+
const body = text.startsWith("\uFEFF") ? "\uFEFFa" : "a";
|
|
163
|
+
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: [body] }]);
|
|
164
|
+
assert.deepEqual(r, { ok: true, text, changed: false, touchedLines: [], contextLines: [] });
|
|
165
|
+
const invalid = applyEdits(text, [{ op: "replace", start: at("wrong\nb\n", 1), body: [body] }]);
|
|
166
|
+
assert.ok(!invalid.ok && invalid.failure.kind === "anchor");
|
|
167
|
+
}
|
|
165
168
|
});
|
|
166
169
|
|
|
167
170
|
test("unrelated change elsewhere does NOT block the edit (no global stale check)", () => {
|
|
@@ -230,8 +233,7 @@ test("appending to a file without a final newline keeps it absent", () => {
|
|
|
230
233
|
test("noop is still detected when the file lacks a final newline", () => {
|
|
231
234
|
const text = "a\nb";
|
|
232
235
|
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["a"] }]);
|
|
233
|
-
assert.
|
|
234
|
-
if (!r.ok) assert.equal(r.failure.kind, "noop");
|
|
236
|
+
assert.deepEqual(r, { ok: true, text, changed: false, touchedLines: [], contextLines: [] });
|
|
235
237
|
});
|
|
236
238
|
|
|
237
239
|
// --- shifted-anchor recovery ---
|
|
@@ -246,6 +248,7 @@ test("shifted recovery: content moved down → found with a fresh anchor", () =>
|
|
|
246
248
|
assert.equal(f.recovery.kind, "found");
|
|
247
249
|
if (f.recovery.kind === "found") {
|
|
248
250
|
assert.equal(f.recovery.newLine, 4);
|
|
251
|
+
assert.equal(f.recovery.scope, "local");
|
|
249
252
|
// the rescued anchor must verify against the current file
|
|
250
253
|
assert.equal(computeLineHash(4, splitLines(currentText)[3]), f.recovery.newHash);
|
|
251
254
|
}
|
|
@@ -280,6 +283,7 @@ test("shifted recovery: duplicate content → ambiguous candidates", () => {
|
|
|
280
283
|
const f = r.failure.failures[0];
|
|
281
284
|
assert.equal(f.recovery.kind, "ambiguous");
|
|
282
285
|
if (f.recovery.kind === "ambiguous") {
|
|
286
|
+
assert.equal(f.recovery.scope, "local");
|
|
283
287
|
assert.deepEqual(
|
|
284
288
|
f.recovery.candidates.map((c) => c.line),
|
|
285
289
|
[3, 5],
|
|
@@ -300,6 +304,38 @@ test("shifted recovery: content genuinely changed → none, with live content",
|
|
|
300
304
|
}
|
|
301
305
|
});
|
|
302
306
|
|
|
307
|
+
test("full-file recovery finds distant content and anchors beyond the current EOF", () => {
|
|
308
|
+
for (const [oldLine, newLine] of [[2, 90], [90, 2], [190, 2]]) {
|
|
309
|
+
const lines = Array.from({ length: 100 }, () => "filler");
|
|
310
|
+
lines[newLine - 1] = "target";
|
|
311
|
+
const result = applyEdits(lines.join("\n"), [
|
|
312
|
+
{ op: "delete", start: { line: oldLine, hash: computeLineHash(oldLine, "target") } },
|
|
313
|
+
]);
|
|
314
|
+
assert.ok(!result.ok && result.failure.kind === "anchor");
|
|
315
|
+
assert.deepEqual(result.failure.failures[0].recovery, {
|
|
316
|
+
kind: "found", scope: "full-file", newLine, newHash: computeLineHash(newLine, "target"),
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
test("full-file recovery collects both sides while preserving local candidate priority", () => {
|
|
322
|
+
for (const { positions, selected, scope } of [
|
|
323
|
+
{ positions: [3, 95], selected: [3, 95], scope: "full-file" },
|
|
324
|
+
{ positions: [3, 49, 95], selected: [49], scope: "local" },
|
|
325
|
+
{ positions: [3, 49, 51, 95], selected: [49, 51], scope: "local" },
|
|
326
|
+
]) {
|
|
327
|
+
const lines = Array.from({ length: 100 }, () => "filler");
|
|
328
|
+
for (const line of positions) lines[line - 1] = "target";
|
|
329
|
+
const result = applyEdits(lines.join("\n"), [
|
|
330
|
+
{ op: "delete", start: { line: 50, hash: computeLineHash(50, "target") } },
|
|
331
|
+
]);
|
|
332
|
+
assert.ok(!result.ok && result.failure.kind === "anchor");
|
|
333
|
+
assert.deepEqual(result.failure.failures[0].recovery, selected.length === 1
|
|
334
|
+
? { kind: "found", scope, newLine: selected[0], newHash: computeLineHash(selected[0], "target") }
|
|
335
|
+
: { kind: "ambiguous", scope, candidates: selected.map(line => ({ line, hash: computeLineHash(line, "target") })) });
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
|
|
303
339
|
test("collect-all: two stale anchors in one batch → both failures returned", () => {
|
|
304
340
|
const readText = "a\nb\nc\nd\n";
|
|
305
341
|
const currentText = "X\na\nb\nc\nd\n"; // inserted X at top → all shifted +1
|
|
@@ -331,7 +367,7 @@ test("rejects CR or LF embedded in body elements", () => {
|
|
|
331
367
|
const result = applyEdits("a\n", [{ op: "append", body }]);
|
|
332
368
|
assert.deepEqual(result, {
|
|
333
369
|
ok: false,
|
|
334
|
-
failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line." },
|
|
370
|
+
failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line.", checks: [] },
|
|
335
371
|
});
|
|
336
372
|
}
|
|
337
373
|
});
|
|
@@ -364,3 +400,44 @@ test("BOM stays at byte zero through first-line edits while anchors retain their
|
|
|
364
400
|
assert.ok(result.ok);
|
|
365
401
|
assert.equal(result.text, "\uFEFFchanged\ninside\uFEFFcontent\n");
|
|
366
402
|
});
|
|
403
|
+
|
|
404
|
+
test("failed batches report every supplied anchor in input order from one snapshot", () => {
|
|
405
|
+
const text = "a\nb\nc\nd\ne\nf\n";
|
|
406
|
+
const stale = { line: 2, hash: "ZZ" };
|
|
407
|
+
const edits: Edit[] = [
|
|
408
|
+
{ op: "replace", start: at(text, 1), end: stale, body: ["A"] },
|
|
409
|
+
{ op: "delete", start: stale, end: at(text, 4) },
|
|
410
|
+
{ op: "insert_after", anchor: at(text, 5), body: ["E"] },
|
|
411
|
+
{ op: "insert_before", anchor: stale, body: ["B"] },
|
|
412
|
+
{ op: "append", body: ["last"] },
|
|
413
|
+
{ op: "prepend", body: ["first"] },
|
|
414
|
+
];
|
|
415
|
+
const result = applyEdits(text, edits);
|
|
416
|
+
assert.ok(!result.ok && result.failure.kind === "anchor");
|
|
417
|
+
assert.deepEqual(result.failure.checks, [
|
|
418
|
+
{ opIndex: 0, op: "replace", which: "anchor", cited: at(text, 1), status: "matched" },
|
|
419
|
+
{ opIndex: 0, op: "replace", which: "end", cited: stale, status: "mismatched" },
|
|
420
|
+
{ opIndex: 1, op: "delete", which: "anchor", cited: stale, status: "mismatched" },
|
|
421
|
+
{ opIndex: 1, op: "delete", which: "end", cited: at(text, 4), status: "matched" },
|
|
422
|
+
{ opIndex: 2, op: "insert_after", which: "anchor", cited: at(text, 5), status: "matched" },
|
|
423
|
+
{ opIndex: 3, op: "insert_before", which: "anchor", cited: stale, status: "mismatched" },
|
|
424
|
+
]);
|
|
425
|
+
const invalid = applyEdits(text, [...edits, { op: "append", body: ["bad\nline"] }]);
|
|
426
|
+
assert.ok(!invalid.ok && invalid.failure.kind === "input");
|
|
427
|
+
assert.deepEqual(invalid.failure.checks, result.failure.checks.map((check) => ({ ...check, status: "not_checked" })));
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
test("matched anchor checks do not imply valid ranges", () => {
|
|
431
|
+
const text = "a\nb\nc\n";
|
|
432
|
+
const cases: { edits: Edit[]; kind: "range"; checks: number }[] = [
|
|
433
|
+
{ edits: [{ op: "delete", start: at(text, 3), end: at(text, 1) }], kind: "range", checks: 2 },
|
|
434
|
+
{ edits: [{ op: "replace", start: at(text, 1), end: at(text, 3), body: ["x"] }, { op: "delete", start: at(text, 2) }], kind: "range", checks: 3 },
|
|
435
|
+
];
|
|
436
|
+
for (const { edits, kind, checks } of cases) {
|
|
437
|
+
const result = applyEdits(text, edits);
|
|
438
|
+
assert.ok(!result.ok);
|
|
439
|
+
assert.equal(result.failure.kind, kind);
|
|
440
|
+
assert.equal(result.failure.checks.length, checks);
|
|
441
|
+
assert.ok(result.failure.checks.every((check) => check.status === "matched"));
|
|
442
|
+
}
|
|
443
|
+
});
|