@criogaid/pi-hashline-edit 0.5.0 → 0.5.1

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 CHANGED
@@ -61,14 +61,14 @@ Successful `edit` and `replace` results omit candidate rows whose full content a
61
61
  | Tool | Use it for |
62
62
  | --- | --- |
63
63
  | `read` | Inspect UTF-8 text with line anchors; Pi-supported images and NUL-containing files use Pi's built-in read. Other invalid UTF-8 is rejected. |
64
- | `grep` | Search with bundled ripgrep and return anchored matches/context, file paths, or counts. |
64
+ | `grep` | Search with bundled ripgrep and return anchored UTF-8 matches/context, plain previews for invalid UTF-8, file paths, or counts. NUL-containing files are skipped. |
65
65
  | `edit` | Change specific lines or ranges using verified anchors. |
66
66
  | `replace` | Replace every occurrence of a literal string or JavaScript regex across one file. |
67
67
  | `write` | Create a file or replace its complete contents. |
68
68
 
69
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 using only forward slashes, such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file`, resolve to native drive paths. Mixed-separator forms such as `/c/dir\file` do not undergo this drive conversion, matching Pi's built-in tools. Mutation tools share the file-mutation queue and commit layer.
70
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.
71
+ Valid UTF-8 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. Invalid UTF-8 grep previews use raw-byte matching as described below.
72
72
 
73
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.
74
74
 
@@ -175,12 +175,12 @@ When the line limit leaves more content, the result reports the shown range and
175
175
  | `pattern` | Required | Non-empty string (including whitespace-only text) or array of non-empty strings; arrays match any pattern (OR). When `ignoreCase` is omitted, smart-case is resolved for the entire query, not separately for each array item. |
176
176
  | `path` | Current directory | Omit `path` to search the working directory. If supplied, it must be one non-empty existing file or directory, or a non-empty array of search roots; `""` and `[]` are invalid. Wildcards are not expanded; use `glob` to filter filenames. |
177
177
  | `glob` | None | One non-empty glob or a non-empty ordered array; prefix exclusions with `!`. |
178
- | `literal` | Automatic | Set `true` for literal code text, including regex punctuation such as `pi.on(`; this does not force case-sensitive matching. Set `false` for intentional ripgrep Rust regex, not JavaScript regex: lookaround and backreferences are unsupported, and `^`/`$` match at line boundaries. Automatic mode tries regex for metacharacters; an invalid single-pattern query falls back to searching the **entire string** literally and reports the fallback. Invalid pattern arrays fail instead of changing their meaning; invalid regex with `literal: false` fails. When the pattern contains lookaround or a backreference, the error or fallback notice says so and points to `replace` for JavaScript regex within one file. |
178
+ | `literal` | Required | `true` matches every pattern as exact text, including regex punctuation such as `pi.on(`; use it for names, paths, and code snippets. It does not force case-sensitive matching. `false` treats every pattern as ripgrep Rust regex, not JavaScript regex: lookaround and backreferences are unsupported, `^`/`$` match at line boundaries, and a valid regex such as `foo(0)` matches `foo0`, not `foo(0)`. An invalid regex fails before any file is searched; when it contains lookaround or a backreference, the error says so and points to `replace` for JavaScript regex within one file, otherwise it suggests `literal: true`. |
179
179
  | `ignoreCase` | Smart-case | Query-level case override: `true` ignores case; `false` distinguishes case. Inline regex case flags may override either setting. |
180
- | `multiline` | `false` | Allow matches across physical lines. CRLF is searched as LF; each distinct matched physical line counts toward `limit` and receives an anchor in content mode. `context` alone does not enable cross-line matching. The `.` wildcard still does not match newlines; use `\n` or `(?s)`. |
181
- | `context` | `0` | Integer from 0 to 20: include that many anchored lines before and after each match (pass 3–5 to inspect code blocks without another read). Fractions are rejected, not rounded. Context lines do not count toward `limit`. |
180
+ | `multiline` | `false` | Allow matches across physical lines. Valid UTF-8 CRLF is searched as LF; each distinct matched physical line counts toward `limit`. Content mode adds anchors only for valid UTF-8 files. `context` alone does not enable cross-line matching. The `.` wildcard still does not match newlines; use `\n` or `(?s)`. |
181
+ | `context` | `0` | Integer from 0 to 20: include that many lines before and after each match (pass 3–5 to inspect code blocks without another read). Fractions are rejected, not rounded. Context lines do not count toward `limit`. |
182
182
  | `limit` | `100` | Positive safe-integer maximum of distinct matching physical lines, across all files and patterns. Reaching the limit produces a notice; it does not prove that another match exists. |
183
- | `outputMode` | `"content"` | `"content"` returns anchored matching lines plus context, `"files"` returns distinct paths, and `"count"` returns matching-line counts per file and a total. All modes use the same limited match set: files and counts may be incomplete when the limit or output byte cap is reached. |
183
+ | `outputMode` | `"content"` | `"content"` returns matching lines plus context, with anchors for valid UTF-8 or plain line numbers for invalid UTF-8; `"files"` returns distinct paths, and `"count"` returns matching-line counts per file and a total. All modes use the same limited match set: files and counts may be incomplete when the limit or output byte cap is reached. |
184
184
 
185
185
  The six former grep fields (`matchMode`, `excludePattern`, `wordMatch`, `pcre2`, `follow`, `noIgnore`) are no longer supported. Calls that contain them, including `false` or `null`, fail before searching; saved session history remains readable, but replaying an old call with these fields requires a new query. They are not silently converted to a different search.
186
186
 
@@ -188,9 +188,13 @@ Grep defaults to line-based code searches. With `multiline: true`, OR patterns a
188
188
 
189
189
  Directory traversal respects ignore rules, does not follow symbolic links, and includes hidden files. Explicitly named files can still be read through a link or from an ignored directory; ordered `glob` filters still apply to explicit file paths. These rules have different priorities for explicit paths and directory traversal and are not simply intersected.
190
190
 
191
- Searches use bundled ripgrep on the shared LF view, independent of system `rg` or `PATH`. The tool disables external ripgrep configuration with `--no-config` and clears `RIPGREP_CONFIG_PATH`, and uses `--no-crlf` and `--encoding=none` so standalone CR and BOM remain content. NUL-containing files are searched as raw bytes; confirmed content-mode hits are rejected before anchoring, and multiline hits are rejected before mapping physical lines. Files without CRLF are searched at their original paths; CRLF text is normalized into temporary snapshots using bounded reads and writes. Batches contain up to 64 files or 8 MiB of source data (one large file can exceed that threshold); snapshots are removed after each batch and on failure/cancellation. Match paths refer to original files; text line and column positions refer to logical text. Regexes use ripgrep's default Rust-style engine, not PCRE2.
191
+ Searches use bundled ripgrep, independent of system `rg` or `PATH`. The tool disables external ripgrep configuration with `--no-config` and clears `RIPGREP_CONFIG_PATH`, and uses `--no-crlf` and `--encoding=none` so standalone CR and BOM remain content. NUL-containing files are silently skipped in all output modes, including explicitly named files; they do not consume the match limit. Valid UTF-8 files use the shared LF view: files without CRLF are searched at their original paths, and CRLF text is normalized into temporary snapshots using bounded reads and writes. Batches contain up to 64 files or 8 MiB of source data (one large file can exceed that threshold); snapshots are removed after each batch and on failure/cancellation. Match paths refer to original files. Regexes use ripgrep's default Rust-style engine, not PCRE2.
192
192
 
193
- 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. Search diagnostics have a separate 4 KiB display budget.
193
+ Files with invalid UTF-8 and no NUL remain searchable as raw bytes, without CRLF normalization or encoding conversion. Multiline queries for these files must match their actual separators, such as `\r\n`. Ripgrep's Unicode regex rules still apply; use a byte-mode group such as `(?-u:...)` when the pattern must span malformed bytes. Content-mode output uses replacement characters and plain `LINE│content` rows for the entire file, including context, followed by `Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors`. These previews are not editable anchors. Files/count modes include their confirmed matches. Unmatched invalid UTF-8 files produce no warning. Content output still verifies the file's byte revision before returning results.
194
+
195
+ 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. Search diagnostics have a separate 4 KiB display budget. Ripgrep stderr and batch aggregation each retain up to 64 KiB. All three limits preserve opening context and the final cause where lines fit, and explicitly mark omitted middle text. The shared implementation is [`DiagnosticBuffer`](src/pi/diagnostic-buffer.ts); limits live in [`budgets.ts`](src/pi/budgets.ts) and [`rg-process.ts`](src/pi/rg-process.ts).
196
+
197
+ All file-tool errors retain every text block in the TUI, including validation causes and recovery hints. Short errors are shown in full when collapsed; longer errors use the same collapsed preview and expansion as grep results. Expanding reveals all retained diagnostic text, including edit recovery context and combined Action Fusion failure details. These display limits do not shorten the tool result sent to the model.
194
198
 
195
199
  Long lines show a labeled partial preview of up to 500 UTF-16 units near a reported match column when available; context-only lines and matches without a recorded column 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.
196
200
 
@@ -302,7 +306,11 @@ file unchanged at the end? <--------------------------------------+
302
306
 
303
307
  Once the mutation completes, it stays successful whatever happens to the command: command failure **does not roll back the file**. The command outcome is returned separately in result text and `details.actionFusion`, rather than thrown as failure of the whole mutation.
304
308
 
305
- 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.
309
+ In the TUI, the mutation card owns the mutation's result or error diagnostics, 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.
310
+
311
+ When `then_run.timeout` is supplied, the command card shows the remaining seconds and refreshes once per second even without command output. The countdown starts when the command starts, after mutation and queue waiting. It stops when execution ends; restored unfinished cards show an unknown final status without a countdown. Pi Bash enforces the timeout. Without `timeout`, there is no countdown or implicit time limit. RPC progress includes `timing.timeoutSeconds` and `timing.remainingSeconds` after a timed command starts.
312
+
313
+ Command failures return Pi Bash's diagnostic text to the LLM, including exit or timeout details and whether file changes were saved. Collapsing a TUI card does not shorten the model's result.
306
314
 
307
315
  The Fusion queue holds a file from mutation until its command finishes, so another fused call on the same file cannot change it in between. 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.
308
316
 
@@ -320,7 +328,7 @@ The Fusion queue holds a file from mutation until its command finishes, so anoth
320
328
 
321
329
  ### Hashing and BOM handling
322
330
 
323
- `read` scans text in bounded chunks, validates the whole file, and retains requested line content within its output budget. It reports the total line count and computes hashes for complete output rows. `grep` scans matching files concurrently, retaining only selected matches/context while formatting each file's output. Completed workers retain formatted output blocks in discovery order. NUL-containing files are searched as raw bytes and confirmed content-mode hits are rejected before anchoring. Mutation revision checks cover actual bytes.
331
+ `read` scans text in bounded chunks, validates the whole file, and retains requested line content within its output budget. It reports the total line count and computes hashes for complete output rows. `grep` scans matching files concurrently, retaining only selected matches/context while formatting each file's output. Completed workers retain formatted output blocks in discovery order. It skips NUL-containing files and generates anchors only for files whose complete contents are valid UTF-8. Invalid UTF-8 previews and anchored output both retain byte revision checks. Mutation revision checks cover actual bytes.
324
332
 
325
333
  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.
326
334
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
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",
@@ -1,6 +1,7 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { decodeEditableText, decodeUtf8 } from "./text.ts";
3
+ import { createUtf8Decoder, decodeEditableText, decodeUtf8 } from "./text.ts";
4
+ import { UNSUPPORTED_ENCODING } from "./errors.ts";
4
5
 
5
6
  test("decodeUtf8 rejects malformed input instead of replacing bytes", () => {
6
7
  assert.throws(() => decodeUtf8(Uint8Array.from([0xc3, 0x28])), /UNSUPPORTED_ENCODING/);
@@ -13,3 +14,31 @@ test("decodeUtf8 preserves a leading BOM", () => {
13
14
  test("decodeEditableText rejects NUL bytes", () => {
14
15
  assert.throws(() => decodeEditableText(Uint8Array.from([0x61, 0, 0x62])), /UNSUPPORTED_TEXT/);
15
16
  });
17
+
18
+ test("streaming UTF-8 decoders preserve a split BOM in strict and lossy modes", () => {
19
+ for (const mode of ["strict", "lossy"] as const) {
20
+ const decode = createUtf8Decoder(mode);
21
+ assert.equal(decode(Uint8Array.from([0xef]), true), "");
22
+ assert.equal(decode(Uint8Array.from([0xbb, 0xbf, 0x61]), true), "\ufeffa");
23
+ assert.equal(decode(), "");
24
+ }
25
+ });
26
+
27
+ test("lossy decoding replaces malformed bytes and flushes incomplete sequences at EOF", () => {
28
+ const decode = createUtf8Decoder("lossy");
29
+ assert.equal(decode(Uint8Array.from([0xef, 0xbb, 0xbf, 0xff, 0xc3, 0x28]), true), "\ufeff��(");
30
+ assert.equal(decode(Uint8Array.from([0xf0]), true), "");
31
+ assert.equal(decode(Uint8Array.from([0x9f]), true), "");
32
+ assert.equal(decode(), "�");
33
+ });
34
+
35
+ test("strict decoding retains the TextDecoder error as the unsupported encoding cause", () => {
36
+ const isEncodingError = (error: unknown) =>
37
+ error instanceof Error &&
38
+ error.message === UNSUPPORTED_ENCODING &&
39
+ error.cause instanceof TypeError;
40
+ assert.throws(() => createUtf8Decoder("strict")(Uint8Array.from([0xff])), isEncodingError);
41
+ const decode = createUtf8Decoder("strict");
42
+ assert.equal(decode(Uint8Array.from([0xf0, 0x9f]), true), "");
43
+ assert.throws(() => decode(), isEncodingError);
44
+ });
package/src/core/text.ts CHANGED
@@ -9,9 +9,14 @@ export function unwritableTextReason(text: string): string | undefined {
9
9
  return undefined;
10
10
  }
11
11
 
12
- /** Create an independent UTF-8 decoder; streaming calls preserve split code points and the BOM. */
13
- export function createUtf8Decoder() {
14
- const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
12
+ export type Utf8Decoding = "strict" | "lossy";
13
+
14
+ /** Streaming UTF-8 decoding preserves BOM; lossy mode replaces malformed bytes with U+FFFD. */
15
+ export function createUtf8Decoder(mode: Utf8Decoding = "strict") {
16
+ const decoder = new TextDecoder("utf-8", { fatal: mode === "strict", ignoreBOM: true });
17
+ if (mode === "lossy") {
18
+ return (bytes?: Uint8Array, stream = false): string => decoder.decode(bytes, { stream });
19
+ }
15
20
  return (bytes?: Uint8Array, stream = false): string => {
16
21
  try {
17
22
  return decoder.decode(bytes, { stream });