pi-hashline-edit-pro 0.19.2 → 0.20.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 CHANGED
@@ -12,8 +12,8 @@ The original uses 2-character hashes of a 16-character alphabet, with the hash b
12
12
 
13
13
  This fork makes two changes that compound:
14
14
 
15
- 1. **3-character hash length** over a 64-char URL-safe base64 alphabet (up from 2 characters in the upstream), expanding the hash space from 256 to 262,144 buckets.
16
- 2. **Perfect hashing (collision resolution).** When computing hashes for a file, if a line's base hash collides with an already-assigned hash, the next available hash is assigned from a bitset (32KB, 262,144 bits) using a hint cursor for O(1) amortized lookup. This ensures every line gets a unique anchor, even within a 3-character hash space. Two byte-identical lines (e.g. repeated `}` or repeated `import` statements) get different hashes automatically.
15
+ 1. **3-character hash length** over a 62-char alphanumeric alphabet (up from 2 characters in the upstream), expanding the hash space from 256 to 238,328 buckets.
16
+ 2. **Perfect hashing (collision resolution).** When computing hashes for a file, if a line's base hash collides with an already-assigned hash, the next available hash is assigned from a bitset (238,328 bits) using a hint cursor for O(1) amortized lookup. This ensures every line gets a unique anchor, even within a 3-character hash space. Two byte-identical lines (e.g. repeated `}` or repeated `import` statements) get different hashes automatically.
17
17
 
18
18
  ## Installation
19
19
 
@@ -49,7 +49,7 @@ szJ│ console.log("world");
49
49
  _zl│}
50
50
  ```
51
51
 
52
- - `HASH` is a 3-character content hash from the URL-safe base64 alphabet `A-Za-z0-9-_` (e.g. `aB3`). See [Hashing](#hashing) for details.
52
+ - `HASH` is a 3-character content hash from the alphanumeric alphabet `A-Za-z0-9` (e.g. `aB3`). See [Hashing](#hashing) for details.
53
53
 
54
54
  Optional parameters:
55
55
 
@@ -66,10 +66,10 @@ Replaces using the `HASH│content` anchors from `read` output to target lines p
66
66
 
67
67
  ```json
68
68
  {
69
+ "path": "src/main.ts",
69
70
  "changes": [
70
- { "content_lines": [" console.log('hashline');"], "hash_range_inclusive": ["ve7", "ve7"] }
71
- ],
72
- "path": "src/main.ts"
71
+ { "hash_range_inclusive": ["ve7", "ve7"], "content_lines": [" console.log('hashline');"] }
72
+ ]
73
73
  }
74
74
  ```
75
75
 
@@ -77,9 +77,9 @@ Replaces using the `HASH│content` anchors from `read` output to target lines p
77
77
 
78
78
  ```json
79
79
  {
80
- "content_lines": [" console.log('hashline');"],
80
+ "path": "src/main.ts",
81
81
  "hash_range_inclusive": ["ve7", "ve7"],
82
- "path": "src/main.ts"
82
+ "content_lines": [" console.log('hashline');"]
83
83
  }
84
84
  ```
85
85
 
@@ -89,7 +89,7 @@ Replaces using the `HASH│content` anchors from `read` output to target lines p
89
89
  | `content_lines` | Literal replacement content, one string per line (use `[]` to delete the range). |
90
90
 
91
91
  - **Request structure validation.** The request envelope (`path`, `changes` in bulk mode; `path`, `hash_range_inclusive`, `content_lines` in flat mode) and individual edit items are validated before any file I/O. Unknown fields, missing required fields, invalid types, and malformed anchors are rejected with `[E_BAD_SHAPE]` or `[E_BAD_REF]`.
92
- - **Legacy dialect rejected.** The native top-level `oldText`/`newText` (and `old_text`/`new_text`) dialect is rejected with `[E_LEGACY_SHAPE]`. The error message tells the model to call `read` first and send `{content_lines: [...], hash_range_inclusive: ["<START>", "<END>"]}`.
92
+ - **Legacy dialect rejected.** The native top-level `oldText`/`newText` (and `old_text`/`new_text`) dialect is rejected with `[E_LEGACY_SHAPE]`. The error message tells the model to call `read` first and send `{hash_range_inclusive: ["<START>", "<END>"], content_lines: [...]}`.
93
93
  - **Batched atomicity (bulk mode).** All edits in a single call validate against the same pre-edit snapshot and apply bottom-up, so the hashes from a single `read` call remain valid across all edits in the batch.
94
94
 
95
95
  ### Stable hashing across edits
@@ -169,13 +169,13 @@ The file is created automatically when any setting is toggled. Both fields are i
169
169
  | `[E_BAD_OP]` | Range start line is after range end line. |
170
170
  | `[E_EDIT_CONFLICT]` | Two edits in one batch overlap the same original lines. |
171
171
  | `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` instead. |
172
- | `[E_FILE_TOO_LARGE]` | The file exceeds the 262,144-line hashline limit. |
172
+ | `[E_FILE_TOO_LARGE]` | The file exceeds the 238,328-line hashline limit. |
173
173
 
174
174
  ## Design Decisions
175
175
 
176
- - **Stale anchors fail (per-line).** A hash mismatch means that specific line's content changed since the last `read`; the error tells the model to call `read()` to get fresh anchors, then copy the 3-character HASH of the start and end of the range being replaced into `hash_range_inclusive` of the next replace call. Because staleness is per-line, editing or appending lines does **not** invalidate anchors for lines whose content is unchanged — anchors for untouched regions stay valid across edits to other regions.
176
+ - **Stale anchors fail (per-line).** A hash mismatch means that specific line's content changed since the last `read`; the error tells the model to call `read()` to get fresh anchors, then copy the 3-character HASH of the start and end of the range being replaced into `hash_range_inclusive` of the next replace call. When a range has one stale and one still-valid anchor, the error also shows the current lines (with fresh hashes) around the resolved anchor, so the model can re-locate the range without a full re-read. Because staleness is per-line, editing or appending lines does **not** invalidate anchors for lines whose content is unchanged — anchors for untouched regions stay valid across edits to other regions.
177
177
  - **No fallback relocation.** Mismatched anchors are never silently relocated to a "close enough" line. This trades convenience for correctness.
178
- - **Strict patch content.** If `content_lines` contains diff-preview rows — `+HASH│` addition prefixes, `-HASH│` or `- │` deletion rows (the padded format the diff preview emits), or `-N ` numbered deletion rows — the edit is rejected with `[E_INVALID_PATCH]`. This narrowly guards against pasting the tool's own diff-preview rows back as content; standard unified-diff lines (`+x`, `-x`, ` x`, `@@ … @@`) are **not** rejected — they are written literally, since literal content must never be silently altered. Bare `HASH│` content (the first 4 chars of a `content_lines` entry looking like 3 base64 chars + `│`) is rejected with `[E_BARE_HASH_PREFIX]`. When the suspect's prefix happens to match a real file-line anchor, the error message flags that as strong evidence the model copied an anchor from the read output.
178
+ - **Strict patch content.** If `content_lines` contains diff-preview rows — `+HASH│` addition prefixes, `-HASH│` or `- │` deletion rows (the padded format the diff preview emits), or `-N ` numbered deletion rows — the edit is rejected with `[E_INVALID_PATCH]`. This narrowly guards against pasting the tool's own diff-preview rows back as content; standard unified-diff lines (`+x`, `-x`, ` x`, `@@ … @@`) are **not** rejected — they are written literally, since literal content must never be silently altered. Bare `HASH│` content (the first 4 chars of a `content_lines` entry looking like 3 alphanumeric chars + `│`) is rejected with `[E_BARE_HASH_PREFIX]`. When the suspect's prefix happens to match a real file-line anchor, the error message flags that as strong evidence the model copied an anchor from the read output.
179
179
 
180
180
  - **BOM preservation.** A UTF-8 BOM is stripped for display and hashing but restored on write, so edits (and undo) never silently strip a BOM from a file that has one.
181
181
  - **Atomic writes.** Files are written via temp-file-then-rename to avoid corruption from interrupted writes. Symlink chains are resolved so the target file is updated without replacing the symlink. Hard-linked files are updated in place to preserve the shared inode. File permissions are preserved across atomic renames.
@@ -185,17 +185,17 @@ The file is created automatically when any setting is toggled. Both fields are i
185
185
  - **Persistent hash store.** `lineHashes` is async and uses a persistent store to preserve hashes for unchanged lines across edits. The store is a SQLite database at `~/.config/pi-hashline-edit-pro/hash-store.sqlite` (per-path snapshots keyed by resolved path storing a 64-bit content checksum + line hashes; auto-created on first use). When called from the replace pipeline, it maps old vs new content and copies hashes for unchanged lines. When called from read, it returns saved hashes if the content's checksum matches, otherwise computes fresh hashes via `_lineHashesPure`. Stale snapshots are pruned on session start. This ensures that editing one part of a file does not cascade to change hashes of unrelated lines. Per-operation work scales with the target file, not cumulative history. If the database is corrupt or unreadable it is quarantined (renamed to `hash-store.sqlite.corrupt-<timestamp>`) and rebuilt from content on the next session start — the store is a cache, never a source of truth.
186
186
  ## Hashing
187
187
 
188
- Hashes are computed with [xxhash-wasm](https://github.com/jungomi/xxhash-wasm) (xxHash32 via WebAssembly), then mapped to a 3-character string from the URL-safe base64 alphabet `A-Za-z0-9-_`. That's 64 distinct characters, 6 bits per position, 18 bits of entropy per anchor.
188
+ Hashes are computed with [xxhash-wasm](https://github.com/jungomi/xxhash-wasm) (xxHash32 via WebAssembly), then mapped to a 3-character string from the alphanumeric alphabet `A-Za-z0-9`. That's 62 distinct characters, 62³ = 238,328 possible anchors (≈17.9 bits of entropy per anchor).
189
189
 
190
- The alphabet is sized for an LLM consumer. The model tokenizes, it doesn't squint at pixel glyphs, so the human-readability heuristics used by smaller hand-curated alphabets (no G/L/I/O because they look like digits, no vowels so the hash doesn't accidentally spell a word, no hex digits so it can't be confused with `0xFF`) don't apply. The full 64 chars give maximum entropy per character, with case and digits included.
190
+ The alphabet is sized for an LLM consumer. The model tokenizes, it doesn't squint at pixel glyphs, so the human-readability heuristics used by smaller hand-curated alphabets (no G/L/I/O because they look like digits, no vowels so the hash doesn't accidentally spell a word, no hex digits so it can't be confused with `0xFF`) don't apply — case and digits are all included. The URL-safe specials `-` and `_` are deliberately excluded: a hash starting with `-` is shape-identical to a diff-preview deletion row (`-HASH│`), and `-`/`_` at a line start are markdown-active (list bullet, emphasis), so they invite mis-copying and false `[E_INVALID_PATCH]`/`[E_BARE_HASH_PREFIX]` rejections. The 9% hash-space cost (238,328 vs 262,144) is irrelevant for real files.
191
191
 
192
192
  Before hashing, each line is normalized: carriage returns are stripped and trailing whitespace is trimmed. This `canon()` normalization prevents insignificant whitespace changes from cascade-triggering hash churn across the file. Two lines that differ only in trailing spaces or `\r` characters produce the same hash, so anchor stability is preserved across editor-save cycles that add or remove trailing whitespace.
193
193
 
194
- **Perfect hashing (collision resolution):** When computing hashes for a file, if a line's base hash collides with an already-assigned hash, the next available hash is assigned from a bitset (32KB, 262,144 bits) using a hint cursor for O(1) amortized lookup. This ensures every line in a file gets a unique anchor, even with the shorter 3-character hash space. Two byte-identical lines (e.g. repeated `}` or repeated `import` statements) get different hashes automatically.
194
+ **Perfect hashing (collision resolution):** When computing hashes for a file, if a line's base hash collides with an already-assigned hash, the next available hash is assigned from a bitset (238,328 bits) using a hint cursor for O(1) amortized lookup. This ensures every line in a file gets a unique anchor, even with the shorter 3-character hash space. Two byte-identical lines (e.g. repeated `}` or repeated `import` statements) get different hashes automatically.
195
195
  The runtime always precomputes the full per-line hash array for a file via `lineHashes(content, path)`, then looks up by line number during validation and during `read` / `replace` response formatting. There is no per-line recomputation that could disagree with what the model saw in its last read. When `path` is provided, `lineHashes` uses a persistent store to preserve hashes for unchanged lines across edits — see [Stable hashing across edits](#stable-hashing-across-edits).
196
196
  `HASH_LEN` in `src/hashline/hash.ts` sets the hash body length; bump it to 4 if you need even more entropy without collision resolution.
197
197
 
198
- The 3-character space holds 262,144 unique anchors, so files are capped at 262,144 lines: `read` and `replace` reject larger files with `[E_FILE_TOO_LARGE]` (use `write` or a non-line-based approach for very large files).
198
+ The 3-character space holds 238,328 unique anchors, so files are capped at 238,328 lines: `read` and `replace` reject larger files with `[E_FILE_TOO_LARGE]` (use `write` or a non-line-based approach for very large files).
199
199
 
200
200
  ### Bare-prefix detector
201
201
 
package/index.ts CHANGED
@@ -15,11 +15,11 @@ import { loadHashStore, pruneMissing } from "./src/hash-store";
15
15
  import { readNormFile } from "./src/file-reader";
16
16
  import { toCwd } from "./src/paths";
17
17
  import { resolveTarget } from "./src/fs-write";
18
- function registerReplaceTool(pi: ExtensionAPI, mode: string, autoRead?: boolean): void {
18
+ function registerReplaceTool(pi: ExtensionAPI, mode: string): void {
19
19
  if (mode === "flat") {
20
- regReplaceFlat(pi, autoRead);
20
+ regReplaceFlat(pi);
21
21
  } else {
22
- regReplace(pi, autoRead);
22
+ regReplace(pi);
23
23
  }
24
24
  }
25
25
 
@@ -46,7 +46,7 @@ export default function (pi: ExtensionAPI): void {
46
46
  const config = await readConfig();
47
47
  const mode = config.replaceMode;
48
48
  autoRead = config.autoRead;
49
- registerReplaceTool(pi, mode, autoRead);
49
+ registerReplaceTool(pi, mode);
50
50
 
51
51
 
52
52
  if (debugValue === "1" || debugValue === "true") {
@@ -58,7 +58,7 @@ export default function (pi: ExtensionAPI): void {
58
58
  description: "Toggle replace tool between bulk (changes array) and flat (single edit at top level) mode",
59
59
  handler: async (_args, ctx) => {
60
60
  const mode = await toggleReplaceMode();
61
- registerReplaceTool(pi, mode, autoRead);
61
+ registerReplaceTool(pi, mode);
62
62
  ctx.ui.notify(`Replace mode switched to: ${mode}`, "info");
63
63
  },
64
64
  });
@@ -68,7 +68,7 @@ export default function (pi: ExtensionAPI): void {
68
68
  handler: async (_args, ctx) => {
69
69
  autoRead = await toggleAutoRead();
70
70
  const mode = (await readConfig()).replaceMode;
71
- registerReplaceTool(pi, mode, autoRead);
71
+ registerReplaceTool(pi, mode);
72
72
  const state = autoRead ? "enabled" : "disabled";
73
73
  ctx.ui.notify(`Auto-read after write/replace: ${state}`, "info");
74
74
  },
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "pi-hashline-edit-pro",
3
- "version": "0.19.2",
3
+ "version": "0.20.0",
4
4
  "type": "module",
5
- "description": "Strict hashline read/replace tool for pi-coding-agent with hash-anchored edits (3-char, 18-bit, perfect hashing)",
5
+ "description": "Strict hashline read/replace tool for pi-coding-agent with hash-anchored edits (3-char, 62-symbol, perfect hashing)",
6
6
  "main": "index.ts",
7
7
  "repository": {
8
8
  "type": "git",
package/prompts/read.md CHANGED
@@ -1 +1 @@
1
- Read a text file; each line returned as HASH│content with a 3-char URL-safe base64 hash. No line numbers — use the HASH as the anchor in replace calls. Images → visual attachments; Binary/directory → rejected; empty → HASH│ (replace to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.
1
+ Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. No line numbers — use the HASH as the anchor in replace calls. Images → visual attachments; Binary/directory → rejected; empty → HASH│ (replace to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.
@@ -1,3 +1,3 @@
1
- - `replace`: content_lines is a native JSON array of strings — never a serialized JSON string; strip the HASH│ prefix from read output and keep leading whitespace exactly as shown after │; no line numbers or diff markers.
2
1
  - `replace`: hash_range_inclusive must use only anchors from the most recent read of the same file; on [E_STALE_ANCHOR], re-read the file and retry with fresh anchors.
2
+ - `replace`: content_lines is a native JSON array of strings — never a serialized JSON string; strip the HASH│ prefix from read output and keep leading whitespace exactly as shown after │; no line numbers or diff markers.
3
3
  - `replace`: minimize the replaced range — anchor only the lines that actually change; for insertions use a single-line range (e.g. the line after the insertion point) instead of a whole block, so fewer unchanged lines must be reproduced byte-exact.
package/src/constants.ts CHANGED
@@ -3,7 +3,7 @@ export const SNIFF_BYTES = 8192;
3
3
  export const MAX_BYTES = 100 * 1024 * 1024;
4
4
 
5
5
  export const HASH_STORE_BUSY_TIMEOUT = 1000;
6
- export const HASH_STORE_VERSION = 3;
6
+ export const HASH_STORE_VERSION = 4;
7
7
  export const CONTENT_LINES_NOT_STRING_MSG =
8
8
  `[E_BAD_SHAPE] "content_lines" must be a native JSON array of strings, not a JSON string.`
9
9
  + ` Do not serialize the array (e.g. '["line1", "line2"]') — pass it as a proper JSON array: ["line1", "line2"].`;
package/src/fs-write.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  stat,
11
11
  writeFile,
12
12
  copyFile,
13
+ chmod,
13
14
  } from "fs/promises";
14
15
  import { dirname, join, parse, resolve, sep } from "path";
15
16
  import { errCode } from "./utils";
@@ -73,6 +74,7 @@ export async function resolveTarget(path: string): Promise<string> {
73
74
  }
74
75
 
75
76
  const TEMP_PREFIX = ".tmp-";
77
+ const TEMP_UUID_RE = /^\.tmp-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
76
78
  const STALE_TEMP_MS = 60 * 60 * 1000;
77
79
  const sweptDirs = new Set<string>();
78
80
 
@@ -83,7 +85,7 @@ async function sweepStaleTemps(dir: string): Promise<void> {
83
85
  const entries = await readdir(dir, { withFileTypes: true });
84
86
  const now = Date.now();
85
87
  for (const entry of entries) {
86
- if (!entry.isFile() || !entry.name.startsWith(TEMP_PREFIX)) continue;
88
+ if (!entry.isFile() || !TEMP_UUID_RE.test(entry.name)) continue;
87
89
  const tempPath = join(dir, entry.name);
88
90
  try {
89
91
  const stats = await stat(tempPath);
@@ -154,6 +156,9 @@ export async function writeAtomic(
154
156
  if (errCode(error) === "EXDEV") {
155
157
  try {
156
158
  await copyFile(tempPath, targetPath);
159
+ if (existingStats) {
160
+ await chmod(targetPath, existingStats.mode & 0o7777);
161
+ }
157
162
  await rm(tempPath, { force: true });
158
163
  await syncDir(dir);
159
164
  return;
@@ -14,9 +14,7 @@ export const ANCHOR_LEN = HASH_LEN;
14
14
  export const HASH_SEP = "│";
15
15
 
16
16
  const ALPH =
17
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
18
- const ALPH_BITS = 6;
19
- const ALPH_MASK = (1 << ALPH_BITS) - 1;
17
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
20
18
  const ALPH_SAFE = ALPH.replace(/-/g, "\\-");
21
19
  const ALPH_RE = new RegExp(`^[${ALPH_SAFE}]+$`);
22
20
  export const HASH_CLASS = `[${ALPH_SAFE}]{${HASH_LEN}}`;
@@ -27,15 +25,22 @@ export const MAX_HASH_LINES = HASH_SPACE;
27
25
  function idxToHash(idx: number): string {
28
26
  let out = "";
29
27
  for (let j = 0; j < HASH_LEN; j++) {
30
- out += ALPH[(idx >>> ((HASH_LEN - 1 - j) * ALPH_BITS)) & ALPH_MASK]!;
28
+ out = ALPH[idx % ALPH.length]! + out;
29
+ idx = Math.floor(idx / ALPH.length);
31
30
  }
32
31
  return out;
33
32
  }
34
33
 
35
- const HASH_TABLE: string[] = Array.from(
36
- { length: HASH_SPACE },
37
- (_, i) => idxToHash(i),
38
- );
34
+ const hashCache = new Map<number, string>();
35
+
36
+ function hashAt(idx: number): string {
37
+ let hash = hashCache.get(idx);
38
+ if (hash === undefined) {
39
+ hash = idxToHash(idx);
40
+ hashCache.set(idx, hash);
41
+ }
42
+ return hash;
43
+ }
39
44
 
40
45
  export const HL_PREFIX_PLUS_RE = new RegExp(
41
46
  `^\\+\\s*${HASH_CLASS}│`,
@@ -63,22 +68,24 @@ function setBit(bits: Uint32Array, idx: number): void {
63
68
 
64
69
  function nextZeroBit(bits: Uint32Array, start: number): number {
65
70
  const totalWords = bits.length;
66
- const totalBits = totalWords * 32;
71
+ const totalBits = HASH_SPACE;
72
+ const lastWordBits = HASH_SPACE - (totalWords - 1) * 32;
67
73
 
68
74
  if (start >= totalBits) start = 0;
69
75
 
70
76
  const wordIdx = start >>> 5;
71
77
  const bitOffset = start & 31;
78
+ const wordBits = (w: number): number => (w === totalWords - 1 ? lastWordBits : 32);
72
79
 
73
80
  let word = bits[wordIdx];
74
- for (let b = bitOffset; b < 32; b++) {
81
+ for (let b = bitOffset; b < wordBits(wordIdx); b++) {
75
82
  if ((word >>> b & 1) === 0) return wordIdx * 32 + b;
76
83
  }
77
84
 
78
85
  for (let w = wordIdx + 1; w < totalWords; w++) {
79
86
  word = bits[w];
80
87
  if (~word !== 0) {
81
- for (let b = 0; b < 32; b++) {
88
+ for (let b = 0; b < wordBits(w); b++) {
82
89
  if ((word >>> b & 1) === 0) return w * 32 + b;
83
90
  }
84
91
  }
@@ -87,7 +94,7 @@ function nextZeroBit(bits: Uint32Array, start: number): number {
87
94
  for (let w = 0; w < wordIdx; w++) {
88
95
  word = bits[w];
89
96
  if (~word !== 0) {
90
- for (let b = 0; b < 32; b++) {
97
+ for (let b = 0; b < wordBits(w); b++) {
91
98
  if ((word >>> b & 1) === 0) return w * 32 + b;
92
99
  }
93
100
  }
@@ -107,13 +114,13 @@ function assignHash(used: Uint32Array, baseIdx: number, hint: { value: number })
107
114
  if (!getBit(used, baseIdx)) {
108
115
  setBit(used, baseIdx);
109
116
  hint.value = baseIdx + 1;
110
- return HASH_TABLE[baseIdx];
117
+ return hashAt(baseIdx);
111
118
  }
112
119
  const start = hint.value > baseIdx + 1 ? hint.value : baseIdx + 1;
113
120
  const nextIdx = nextZeroBit(used, start);
114
121
  setBit(used, nextIdx);
115
122
  hint.value = nextIdx + 1;
116
- return HASH_TABLE[nextIdx];
123
+ return hashAt(nextIdx);
117
124
  }
118
125
 
119
126
  export function _lineHashesPure(content: string): string[] {
@@ -124,7 +131,7 @@ export function _lineHashesPure(content: string): string[] {
124
131
 
125
132
  for (let i = 0; i < lines.length; i++) {
126
133
  const c = canon(lines[i]!);
127
- const baseIdx = xxh32(c) >>> 14;
134
+ const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
128
135
  hashes[i] = assignHash(used, baseIdx, hint);
129
136
  }
130
137
  return hashes;
@@ -172,7 +179,7 @@ function hashToIndex(hash: string): number {
172
179
  for (let j = 0; j < HASH_LEN; j++) {
173
180
  const charIdx = ALPH.indexOf(hash[j]!);
174
181
  if (charIdx < 0) return -1;
175
- idx = (idx << ALPH_BITS) | charIdx;
182
+ idx = idx * ALPH.length + charIdx;
176
183
  }
177
184
  return idx;
178
185
  }
@@ -283,7 +290,7 @@ function mapStableHashes(
283
290
  for (let i = 0; i < newLines.length; i++) {
284
291
  if (newHashes[i]) continue;
285
292
  const c = canon(newLines[i]!);
286
- const baseIdx = xxh32(c) >>> 14;
293
+ const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
287
294
  newHashes[i] = assignHash(used, baseIdx, hint);
288
295
  }
289
296
 
@@ -14,7 +14,7 @@ function diagRef(ref: string): string {
14
14
  const trimmed = ref.trim();
15
15
 
16
16
  if (!trimmed.length) {
17
- return `[E_BAD_REF] Invalid anchor. Expected a 3-char base64 anchor (e.g. "aB3").`;
17
+ return `[E_BAD_REF] Invalid anchor. Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
18
18
  }
19
19
 
20
20
  if (/^\d+/.test(trimmed)) {
@@ -25,7 +25,7 @@ function diagRef(ref: string): string {
25
25
  return `[E_BAD_REF] Invalid anchor "${trimmed}". hash_range_inclusive must contain the 3-char hash only — remove everything from "│" onward.`;
26
26
  }
27
27
 
28
- return `[E_BAD_REF] Invalid anchor "${trimmed}". Expected a 3-char base64 anchor (e.g. "aB3").`;
28
+ return `[E_BAD_REF] Invalid anchor "${trimmed}". Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
29
29
  }
30
30
 
31
31
  function parseRef(ref: string): Anchor {
@@ -59,7 +59,9 @@ function assertNoPrefixes(lines: string[]): void {
59
59
  }
60
60
 
61
61
  export function parseText(edit: string[] | string | null): string[] {
62
- if (edit === null) return [];
62
+ if (edit === null) {
63
+ throw new Error('[E_BAD_SHAPE] "content_lines" must be a string array; use [] to delete a range.');
64
+ }
63
65
  if (typeof edit === "string") {
64
66
  throw new Error(CONTENT_LINES_NOT_STRING_MSG);
65
67
  }
@@ -19,6 +19,7 @@ interface HMismatch {
19
19
  ref: Anchor;
20
20
  kind: "not_found" | "ambiguous";
21
21
  candidates?: number[];
22
+ context?: RAnchor;
22
23
  }
23
24
 
24
25
  export interface BDupWarn {
@@ -95,6 +96,18 @@ export function fmtMismatch(
95
96
  out.push(
96
97
  `[E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. The file content has changed since those anchors were read. Call read() to get fresh anchors, then copy the 3-char HASH of the start and end of the range you are replacing into hash_range_inclusive of your next replace call.`
97
98
  );
99
+ for (const m of notFound) {
100
+ const ctx = m.context;
101
+ if (!ctx) continue;
102
+ const from = Math.max(1, ctx.line - 1);
103
+ const to = Math.min(fileLines.length, ctx.line + 1);
104
+ const rows: string[] = [];
105
+ for (let ln = from; ln <= to; ln++) {
106
+ rows.push(` ${ln}: ${fileHashes[ln - 1]}│${clipLine(fileLines[ln - 1] ?? "")}`);
107
+ }
108
+ out.push("");
109
+ out.push(` Current context around resolved anchor "${ctx.hash}" (line ${ctx.line}):\n${rows.join("\n")}`);
110
+ }
98
111
  }
99
112
  if (ambiguous.length > 0) {
100
113
  if (out.length > 0) out.push("");
@@ -297,6 +310,13 @@ export function valEdits(
297
310
  const startResolved = tryResolve(edit.hash_range_inclusive[0]);
298
311
  const endResolved = tryResolve(edit.hash_range_inclusive[1]);
299
312
  if (!startResolved || !endResolved) {
313
+ if (!startResolved && endResolved) {
314
+ const startMismatch = mismatches.findLast((m) => m.ref === edit.hash_range_inclusive[0]);
315
+ if (startMismatch && startMismatch.kind === "not_found") startMismatch.context = endResolved;
316
+ } else if (startResolved && !endResolved) {
317
+ const endMismatch = mismatches.findLast((m) => m.ref === edit.hash_range_inclusive[1]);
318
+ if (endMismatch && endMismatch.kind === "not_found") endMismatch.context = startResolved;
319
+ }
300
320
  continue;
301
321
  }
302
322
  if (startResolved.line > endResolved.line) {
package/src/read.ts CHANGED
@@ -30,7 +30,7 @@ function normPosInt(
30
30
  }
31
31
 
32
32
  if (!Number.isInteger(value) || value < 1) {
33
- throw new Error(`Read request field "${name}" must be a positive integer.`);
33
+ throw new Error(`[E_BAD_SHAPE] Read request field "${name}" must be a positive integer.`);
34
34
  }
35
35
 
36
36
  return value;
@@ -45,7 +45,6 @@ export function genDiff(
45
45
  newContent: string,
46
46
  contextLines = 2,
47
47
  newContentHashes?: string[],
48
- _oldHashes?: string[],
49
48
  ): { diff: string; firstChangedLine: number | undefined } {
50
49
  const effectiveNewHashes = newContentHashes ?? _lineHashesPure(newContent);
51
50
 
@@ -78,7 +78,7 @@ export function normReq(input: unknown): unknown {
78
78
  const hri = record.hash_range_inclusive;
79
79
  const cl = record.content_lines;
80
80
  if (Array.isArray(hri) && Array.isArray(cl)) {
81
- record.changes = [{ content_lines: cl, hash_range_inclusive: hri }];
81
+ record.changes = [{ hash_range_inclusive: hri, content_lines: cl }];
82
82
  delete record.hash_range_inclusive;
83
83
  delete record.content_lines;
84
84
  }
@@ -129,10 +129,10 @@ export function buildNoop(input: NoopInput): TResult {
129
129
  }
130
130
 
131
131
  export function buildChanged(input: SuccessInput): TResult {
132
- const { path, result, warnings, snapshotId, originalNormalized, originalHashes, editMeta, resultHashes } = input;
132
+ const { path, result, warnings, snapshotId, originalNormalized, editMeta, resultHashes } = input;
133
133
 
134
134
  const resultLines = visLines(result);
135
- const diffResult = genDiff(originalNormalized, result, 2, resultHashes, originalHashes);
135
+ const diffResult = genDiff(originalNormalized, result, 2, resultHashes);
136
136
  const addedLines = editMeta.addedLines;
137
137
  const removedLines = editMeta.removedLines;
138
138
  const warningsBlock = warnBlock(warnings);
@@ -85,8 +85,12 @@ export function regReplaceUndo(pi: ExtensionAPI): void {
85
85
  undo.bom + restoreEndings(undo.content, undo.originalEnding),
86
86
  );
87
87
 
88
- const store = await loadHashStore();
89
- upsertSnapshot(store, mutationTargetPath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
88
+ try {
89
+ const store = await loadHashStore();
90
+ upsertSnapshot(store, mutationTargetPath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
91
+ } catch (error) {
92
+ console.error("Failed to restore hash store snapshot after undo:", error);
93
+ }
90
94
 
91
95
  clearUndo(mutationTargetPath);
92
96
 
package/src/replace.ts CHANGED
@@ -59,25 +59,25 @@ const hashRangeInclSchema = Type.Array(
59
59
 
60
60
  const changeItemSchema = Type.Object(
61
61
  {
62
- content_lines: contentLinesSchema,
63
62
  hash_range_inclusive: hashRangeInclSchema,
63
+ content_lines: contentLinesSchema,
64
64
  },
65
65
  { additionalProperties: false },
66
66
  );
67
67
 
68
68
  export const editToolSchema = Type.Object(
69
69
  {
70
- changes: Type.Array(changeItemSchema, { description: "Array of edits applied atomically against the same pre-edit snapshot." }),
71
70
  path: Type.String({ description: "Path to edit" }),
71
+ changes: Type.Array(changeItemSchema, { description: "Array of edits applied atomically against the same pre-edit snapshot." }),
72
72
  },
73
73
  { additionalProperties: false },
74
74
  );
75
75
 
76
76
  export const flatEditToolSchema = Type.Object(
77
77
  {
78
- content_lines: contentLinesSchema,
79
- hash_range_inclusive: hashRangeInclSchema,
80
78
  path: Type.String({ description: "Path to edit" }),
79
+ hash_range_inclusive: hashRangeInclSchema,
80
+ content_lines: contentLinesSchema,
81
81
  },
82
82
  { additionalProperties: false },
83
83
  );
@@ -123,7 +123,7 @@ export function assertNoLegacyKeys(request: unknown): void {
123
123
  for (const legacyKey of LEGACY_KS) {
124
124
  if (has(request, legacyKey)) {
125
125
  throw new Error(
126
- `[E_LEGACY_SHAPE] "${legacyKey}" is not supported. Use {content_lines: [...], hash_range_inclusive: ["<START>", "<END>"]}.`
126
+ `[E_LEGACY_SHAPE] "${legacyKey}" is not supported. Use {hash_range_inclusive: ["<START>", "<END>"], content_lines: [...]}.`
127
127
  );
128
128
  }
129
129
  }
@@ -148,10 +148,10 @@ export function assertReq(
148
148
  if (!Array.isArray(request.changes)) {
149
149
  if (flat) {
150
150
  throw new Error(
151
- '[E_BAD_SHAPE] Edit request requires both "content_lines" and "hash_range_inclusive" at the top level.',
151
+ '[E_BAD_SHAPE] Edit request requires both "hash_range_inclusive" and "content_lines" at the top level.',
152
152
  );
153
153
  }
154
- throw new Error('[E_BAD_SHAPE] Edit request requires a "changes" array. Each change is { content_lines: [...], hash_range_inclusive: ["<START>", "<END>"] }.');
154
+ throw new Error('[E_BAD_SHAPE] Edit request requires a "changes" array. Each change is { hash_range_inclusive: ["<START>", "<END>"], content_lines: [...] }.');
155
155
  }
156
156
  }
157
157
 
@@ -283,11 +283,11 @@ export async function compPreview(
283
283
  const normalized = normReq(request);
284
284
  if (flat && isRec(request) && Array.isArray(request.changes)) {
285
285
  return {
286
- error: `[E_BAD_SHAPE] Flat mode does not accept a "changes" array. Send content_lines and hash_range_inclusive at the top level (one edit per call), or use bulk mode for multiple edits per call.`
286
+ error: `[E_BAD_SHAPE] Flat mode does not accept a "changes" array. Send hash_range_inclusive and content_lines at the top level (one edit per call), or use bulk mode for multiple edits per call.`
287
287
  };
288
288
  }
289
289
  assertReq(normalized, flat);
290
- const { path, originalNormalized, originalHashes, result, resultHashes } = await execPipeline(
290
+ const { path, originalNormalized, result, resultHashes } = await execPipeline(
291
291
  normalized,
292
292
  cwd,
293
293
  { accessMode: constants.R_OK, noPersist: true },
@@ -299,7 +299,7 @@ export async function compPreview(
299
299
  };
300
300
  }
301
301
 
302
- return { diff: genDiff(originalNormalized, result, 4, resultHashes, originalHashes).diff };
302
+ return { diff: genDiff(originalNormalized, result, 4, resultHashes).diff };
303
303
  } catch (error: unknown) {
304
304
  return { error: error instanceof Error ? error.message : String(error) };
305
305
  }
@@ -336,7 +336,7 @@ const MODE_CFG = {
336
336
  },
337
337
  } as const;
338
338
 
339
- export function buildToolDef(opts: { flat: boolean; autoRead?: boolean }): ToolDef {
339
+ export function buildToolDef(opts: { flat: boolean }): ToolDef {
340
340
  const cfg = MODE_CFG[opts.flat ? "flat" : "bulk"];
341
341
 
342
342
  const E_DESC = loadP("../prompts/replace.md");
@@ -554,14 +554,14 @@ export function buildToolDef(opts: { flat: boolean; autoRead?: boolean }): ToolD
554
554
  };
555
555
  }
556
556
 
557
- export function regReplace(pi: ExtensionAPI, autoRead?: boolean): void {
558
- pi.registerTool(buildToolDef({ flat: false, autoRead }));
557
+ export function regReplace(pi: ExtensionAPI): void {
558
+ pi.registerTool(buildToolDef({ flat: false }));
559
559
  }
560
560
 
561
- export function buildToolDefFlat(autoRead?: boolean) {
562
- return buildToolDef({ flat: true, autoRead });
561
+ export function buildToolDefFlat() {
562
+ return buildToolDef({ flat: true });
563
563
  }
564
564
 
565
- export function regReplaceFlat(pi: ExtensionAPI, autoRead?: boolean): void {
566
- pi.registerTool(buildToolDef({ flat: true, autoRead }));
565
+ export function regReplaceFlat(pi: ExtensionAPI): void {
566
+ pi.registerTool(buildToolDef({ flat: true }));
567
567
  }