@criogaid/pi-hashline-edit 0.1.3 → 0.3.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 +77 -23
- package/package.json +1 -1
- package/src/core/apply.test.ts +87 -10
- package/src/core/apply.ts +106 -84
- package/src/core/lines.test.ts +12 -1
- package/src/core/lines.ts +43 -1
- 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 +188 -1
- package/src/pi/action-fusion.test.ts +3 -1
- package/src/pi/action-fusion.ts +38 -35
- package/src/pi/anchor-format.test.ts +30 -0
- package/src/pi/anchor-format.ts +28 -0
- package/src/pi/config.ts +1 -1
- package/src/pi/edit-tool.ts +91 -100
- package/src/pi/execute.test.ts +239 -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 +20 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/fusion-card.test.ts +38 -1
- package/src/pi/fusion-card.ts +41 -17
- package/src/pi/grep-tool.ts +84 -55
- package/src/pi/grep.test.ts +77 -6
- package/src/pi/mutation-result.ts +48 -9
- package/src/pi/path.ts +22 -0
- package/src/pi/pi.test.ts +64 -2
- package/src/pi/read-tool.ts +9 -30
- package/src/pi/registration.test.ts +28 -1
- package/src/pi/render.test.ts +111 -0
- package/src/pi/render.ts +30 -6
- package/src/pi/replace-tool.ts +144 -140
- package/src/pi/replace.test.ts +193 -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 +10 -12
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/rg-text-view.ts +88 -0
- package/src/pi/write-tool.ts +13 -47
- package/src/pi/write.test.ts +25 -36
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ 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
|
|
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
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)
|
|
@@ -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
|
|
|
@@ -64,7 +66,11 @@ Use returned anchors for subsequent edits. Content-mode `grep` provides the same
|
|
|
64
66
|
| `replace` | Replace every occurrence of a literal string or JavaScript regex across one file. |
|
|
65
67
|
| `write` | Create a file or replace its complete contents. |
|
|
66
68
|
|
|
67
|
-
All tools accept relative
|
|
69
|
+
All tools accept relative and absolute paths, `file://` URLs, a leading `@` prefix, and a leading `~` (including `~\` on Windows). As in Pi's built-in file tools, supported Unicode spaces in paths become regular spaces, and Windows shell drive paths such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file` resolve to native drive paths. Mutation tools share the file-mutation queue and commit layer.
|
|
70
|
+
|
|
71
|
+
All text inspection and matching uses one logical representation: CRLF boundaries become LF; standalone CR and source-code escape sequences such as the four characters `\r\n` remain content. `read` and `grep` hash the same logical lines that `edit` verifies; literal and regex `replace` both match this LF view. Mutation offsets map back to the original text. `edit` and `replace` share separator restoration: reuse internal separators positionally, repeat the last for extra gaps, or use the file style (CRLF if present, otherwise LF) when none exist. Boundaries outside the replacement stay unchanged.
|
|
72
|
+
|
|
73
|
+
`write` is the full-content boundary: its supplied bytes are authoritative, so it preserves their explicit LF/CRLF choices. Use it for intentional whole-file line-ending conversion. To inspect actual line-ending bytes, use a raw byte reader; anchored line displays intentionally do not distinguish LF from CRLF.
|
|
68
74
|
|
|
69
75
|
### Edit operations
|
|
70
76
|
|
|
@@ -79,6 +85,18 @@ All tools accept relative or absolute paths and expand a leading `~`. Mutation t
|
|
|
79
85
|
|
|
80
86
|
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
87
|
|
|
88
|
+
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.
|
|
89
|
+
|
|
90
|
+
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.
|
|
91
|
+
|
|
92
|
+
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.
|
|
93
|
+
|
|
94
|
+
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`.
|
|
95
|
+
|
|
96
|
+
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.
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
|
|
82
100
|
### Bulk replacement
|
|
83
101
|
|
|
84
102
|
For a rename across a file:
|
|
@@ -87,12 +105,30 @@ For a rename across a file:
|
|
|
87
105
|
{ "path": "src/foo.ts", "find": "oldName", "replace": "newName" }
|
|
88
106
|
```
|
|
89
107
|
|
|
90
|
-
Literal mode
|
|
108
|
+
Literal mode keeps `$` text verbatim. Both literal and regex modes match the shared LF view: actual CRLF in the file and `find` normalizes to LF; standalone CR remains content. Match ranges map back to the original text before replacement, preserving bytes and separators outside each match, including an unmatched BOM or final newline.
|
|
109
|
+
|
|
110
|
+
Replacement text also normalizes CRLF to LF, then reuses matched separators in order. Additional lines use the last matched separator, or the file style when the match contains no separator (CRLF if present anywhere, otherwise LF).
|
|
111
|
+
|
|
112
|
+
Regex patterns run on LF text, so use `\n` for a line boundary. Captures and replacement templates also use the LF snapshot; the result then restores original separators. Use `write` for explicit line-ending conversion. Source-code escapes are ordinary text: JSON `"find": "\\r\\n"` finds the visible four-character sequence in literal mode, while `"find": "\r\n"` contains an actual CRLF boundary. Set `regex: true` for JavaScript capture groups and replacement templates:
|
|
91
113
|
|
|
92
114
|
```json
|
|
93
115
|
{ "path": "src/foo.ts", "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }
|
|
94
116
|
```
|
|
95
117
|
|
|
118
|
+
To apply several rules against the same original content:
|
|
119
|
+
|
|
120
|
+
```json
|
|
121
|
+
{
|
|
122
|
+
"path": "src/foo.ts",
|
|
123
|
+
"replacements": [
|
|
124
|
+
{ "find": "foo", "replace": "bar" },
|
|
125
|
+
{ "find": "bar", "replace": "baz" }
|
|
126
|
+
]
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
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.
|
|
131
|
+
|
|
96
132
|
<details>
|
|
97
133
|
<summary><strong>Full read, grep, replace, and write parameter reference</strong></summary>
|
|
98
134
|
|
|
@@ -108,7 +144,7 @@ Required: `path`. Optional: 1-based `offset` (default 1) and `limit` (default 20
|
|
|
108
144
|
| `path` | Current directory | One path or an array of search roots. |
|
|
109
145
|
| `matchMode` | `"any"` | OR across patterns; `"all"` requires every pattern on the same physical line, at most 16 patterns. |
|
|
110
146
|
| `excludePattern` | None | String or array; remove lines matching any exclusion. |
|
|
111
|
-
| `literal` | Automatic | `true
|
|
147
|
+
| `literal` | Automatic | Set `true` for code text containing regex punctuation, such as `pi.on(`, `compact(`, or a visible `\0`; use a `pattern` array for literal alternatives. Set `false` only for intentional valid regex. The setting also applies to exclusions. Automatic mode tries regex when it sees metacharacters; an invalid single pattern without exclusions falls back to searching the **entire string** literally, not interpreting `|` as alternatives. Invalid compound queries fail rather than changing their meaning. |
|
|
112
148
|
| `ignoreCase` | Smart-case | Explicit `true`/`false` overrides case handling; the query-level decision also applies to exclusions. |
|
|
113
149
|
| `wordMatch` | `false` | Whole-word matches. |
|
|
114
150
|
| `glob` | None | One glob or an ordered array; prefix exclusions with `!`. |
|
|
@@ -122,17 +158,23 @@ Required: `path`. Optional: 1-based `offset` (default 1) and `limit` (default 20
|
|
|
122
158
|
|
|
123
159
|
Context is rebuilt from surviving matches. Multiline filtering, counting, and limits remain line-based. Wildcard-only regexes such as `.*` and `^.+$` are accepted; use `literal: true` to search those characters verbatim.
|
|
124
160
|
|
|
125
|
-
All inclusion/exclusion matching uses bundled ripgrep, independent of system `rg` or `PATH`.
|
|
161
|
+
All inclusion/exclusion matching uses bundled ripgrep on the shared LF view, independent of system `rg` or `PATH`. File selection uses original paths, ignore rules, globs, and link settings. Search batches stage up to 64 normalized temporary files or 8 MiB of text (one large file can exceed that threshold); snapshots are removed after each batch and on failure/cancellation. This adds temporary disk I/O. Match paths refer to original files; line and column positions refer to logical text. Searches include hidden files and pass `--no-config`, `--no-crlf`, and `--encoding=none` for snapshot matching so standalone CR and BOM remain content. The default engine is Rust regex; PCRE2 never silently falls back to another engine or literal matching.
|
|
162
|
+
|
|
163
|
+
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.
|
|
164
|
+
|
|
165
|
+
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.
|
|
126
166
|
|
|
127
167
|
### Replace
|
|
128
168
|
|
|
129
|
-
Required: `path`, `find`, `replace`.
|
|
169
|
+
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
170
|
|
|
131
|
-
- `regex`: defaults to `false`;
|
|
171
|
+
- `regex`: defaults to `false`; both modes match the shared LF view. Regex mode supports capture groups, the full match, and prefix/suffix substitutions.
|
|
132
172
|
- `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.
|
|
173
|
+
- `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.
|
|
174
|
+
|
|
175
|
+
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 in the original text). Literal and regex rules share the same original ranges for conflict detection.
|
|
134
176
|
|
|
135
|
-
|
|
177
|
+
Regex captures and prefix/suffix substitutions always refer to the original LF-normalized snapshot.
|
|
136
178
|
|
|
137
179
|
### Write
|
|
138
180
|
|
|
@@ -142,8 +184,14 @@ Required: `path`, `content`. By default, create missing files and overwrite exis
|
|
|
142
184
|
- `mode: "overwrite"`: require an existing target.
|
|
143
185
|
- `expectedRevision`: strictly check the current file's SHA-256; cannot be combined with create mode.
|
|
144
186
|
|
|
187
|
+
Write results report the write outcome without returning line anchors. Use `read` or content-mode `grep` to obtain anchors for a later `edit`.
|
|
188
|
+
|
|
189
|
+
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.
|
|
190
|
+
|
|
145
191
|
With Action Fusion enabled, `edit`, `replace`, and `write` also accept `then_run`.
|
|
146
192
|
|
|
193
|
+
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.
|
|
194
|
+
|
|
147
195
|
</details>
|
|
148
196
|
|
|
149
197
|
## Configuration
|
|
@@ -166,7 +214,7 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
|
|
|
166
214
|
| `enabled` | `true` | Enable all five tools as one unit. Set `false` to restore built-in tools. |
|
|
167
215
|
| `actionFusion` | `true` | Expose `then_run` on mutation tools. Set `false` to disable command support. |
|
|
168
216
|
| `hashLen` | `4` | Integer checksum length, 2–8 characters. |
|
|
169
|
-
| `shiftRadius` | `15` | Integer recovery-search radius, 0–100 lines; `0` disables
|
|
217
|
+
| `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
218
|
|
|
171
219
|
The project's `hashlineEdit` object replaces the global object as a whole; missing or invalid fields use defaults. Reload Pi after changes.
|
|
172
220
|
|
|
@@ -185,7 +233,7 @@ Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdi
|
|
|
185
233
|
|
|
186
234
|
`command` is required; `timeout` is optional, in positive seconds, with no default. Mutation failure skips the command. Command failure after mutation success **does not roll back the file**: it is returned separately in result text and `details.actionFusion`, rather than thrown as failure of the whole mutation.
|
|
187
235
|
|
|
188
|
-
In the TUI, the mutation card turns successful when execution and result generation finish. The command
|
|
236
|
+
In the TUI, the mutation card owns the mutation's result or error summary, publication status, and freshness warnings. It turns successful when mutation execution and result generation finish. The command card owns command output and execution status; skipped or cancelled commands are neutral and show a short reason when execution never started. Mutation diagnostics never become command output, and command failure leaves a successful mutation card intact. RPC hosts receive the same progress and choose their own rendering.
|
|
189
237
|
|
|
190
238
|
Fusion serializes each mutation/command sequence for its target and checks the published revision before running the command. Commands invoke Pi's built-in Bash definition directly, without a separate Bash tool call; Bash-only approval/sandbox extensions must explicitly cover these tools' `then_run` inputs.
|
|
191
239
|
|
|
@@ -193,7 +241,7 @@ Fusion serializes each mutation/command sequence for its target and checks the p
|
|
|
193
241
|
|
|
194
242
|
- **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
243
|
- **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
|
|
244
|
+
- **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
245
|
- **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
246
|
- **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
247
|
- **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 +253,8 @@ Fusion serializes each mutation/command sequence for its target and checks the p
|
|
|
205
253
|
|
|
206
254
|
`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
255
|
|
|
256
|
+
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 `details.diff` marks raw CR as `␍`; `details.displayDiff` renders the shared LF view for the TUI, so CRLF boundary markers stay hidden even in mixed-ending files or beside an unterminated last line. Standalone CR and literal `␍` characters remain visible. Unified patches retain the original characters and line endings. The marker is a display aid, not replacement text.
|
|
257
|
+
|
|
208
258
|
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
259
|
|
|
210
260
|
### Output budgets
|
|
@@ -213,18 +263,22 @@ These limits bound model context, not file size. Omission notices direct the cal
|
|
|
213
263
|
|
|
214
264
|
| Output | Limit |
|
|
215
265
|
| --- | --- |
|
|
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
|
-
|
|
|
266
|
+
| `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. |
|
|
267
|
+
| `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. |
|
|
268
|
+
| `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. |
|
|
269
|
+
| 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. |
|
|
270
|
+
| Input-anchor checks | Independent 16 KiB block, with no fixed entry-count limit. Truncation is reported explicitly; omitted entries are not implied matched. |
|
|
271
|
+
| 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. |
|
|
272
|
+
|
|
273
|
+
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
274
|
|
|
222
275
|
### Publication
|
|
223
276
|
|
|
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.
|
|
277
|
+
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
278
|
|
|
226
279
|
| Case | Behavior |
|
|
227
280
|
| --- | --- |
|
|
281
|
+
| No-op | After validation, return existing revisions without creating a temporary file or replacing the target. |
|
|
228
282
|
| Create | Same-filesystem `link(temp, target)` refuses a target created by another writer during publication. |
|
|
229
283
|
| Overwrite | `rename(temp, target)` publishes the replacement; never delete the old target first. |
|
|
230
284
|
| Symlinks | Resolve the regular-file target for overwrite and preserve the link; reject dangling/unresolvable links. |
|
|
@@ -240,11 +294,11 @@ The shared commit layer prepares and syncs complete content in a sibling tempora
|
|
|
240
294
|
| `publication` | `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Fusion also reports it in `actionFusion.publication`. |
|
|
241
295
|
| `baseRevision` | SHA-256 of bytes read before mutation, when available. |
|
|
242
296
|
| `publishedRevision` | SHA-256 of intended published bytes; `revision` is its compatibility alias. |
|
|
243
|
-
| `observedRevision` | SHA-256 observed by the commit layer after publication. |
|
|
297
|
+
| `observedRevision` | SHA-256 observed by the commit layer after publication, or at the no-op check. |
|
|
244
298
|
| `actionFusion.command` | `not_requested`, `skipped`, `succeeded`, `failed`, `timeout`, or `cancelled`. |
|
|
245
299
|
| `actionFusion.freshness` | `unchanged`, `changed`, `missing`, or `unknown`, relative to the published revision. |
|
|
246
300
|
| `actionFusion.mutationCompleted` | Progress flag set after mutation execution and result generation succeed; publication alone is not mutation success. |
|
|
247
301
|
|
|
248
|
-
Streaming mutation summaries omit anchors. Result-generation failures preserve publication status; progress callback failures are reported separately from mutation/command outcomes. Command output
|
|
302
|
+
Streaming mutation summaries omit anchors. Result-generation failures preserve publication status and any completed command outcome; progress callback failures are reported separately from mutation/command outcomes. Command progress `output` contains only command output or execution errors, with an optional `reason` for commands that never started. Command cards persist only their own state and use native Bash output rendering. Final cards survive reloads without adding model-context messages; unfinished saved commands show an interrupted/unknown outcome. Older mixed failure snapshots expose only recognized command diagnostics, leaving other details in the original tool result.
|
|
249
303
|
|
|
250
304
|
</details>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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)", () => {
|
|
@@ -202,8 +205,8 @@ test("replacing one line with several keeps the block's trailing gap", () => {
|
|
|
202
205
|
const result = applyEdits(before, [{ op: "replace", start: at(before, 2), body: ["X", "Y", "Z"] }]);
|
|
203
206
|
assert.equal(result.ok, true);
|
|
204
207
|
// b's gap (\n) moves to the last new line, so the boundary to c is unchanged;
|
|
205
|
-
//
|
|
206
|
-
if (result.ok) assert.equal(result.text, "a\r\nX\nY\r\nZ\nc\r\nd");
|
|
208
|
+
// b has no internal gap; both new internal gaps use the file style, like replace("b", "X\nY\nZ").
|
|
209
|
+
if (result.ok) assert.equal(result.text, "a\r\nX\r\nY\r\nZ\nc\r\nd");
|
|
207
210
|
});
|
|
208
211
|
|
|
209
212
|
test("a file without a final newline keeps not having one", () => {
|
|
@@ -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
|
+
});
|