dsh-better-edit 0.6.3 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,3 +1,32 @@
1
+ ## [0.7.1](https://github.com/Rianico/dsh-better-edit/compare/v0.7.0...v0.7.1) (2026-09-06)
2
+
3
+ ### Bug Fixes
4
+
5
+ * **hashline:** retired hazard GC and stable reuse for anchor-space deadlock ([#59](https://github.com/Rianico/dsh-better-edit/issues/59)) ([2487c43](https://github.com/Rianico/dsh-better-edit/commit/2487c43e6d0ec8e5af15b42495bc4f8d7e3ca89a)), closes [#51](https://github.com/Rianico/dsh-better-edit/issues/51) [#51](https://github.com/Rianico/dsh-better-edit/issues/51) [#51](https://github.com/Rianico/dsh-better-edit/issues/51)
6
+
7
+ ### Documentation
8
+
9
+ * **context:** retired anchor replaces tombstone; add hazard card and epoch glossary ([#58](https://github.com/Rianico/dsh-better-edit/issues/58)) ([287b68e](https://github.com/Rianico/dsh-better-edit/commit/287b68efc97bea940fd881a8ca1e8755b2da311a)), closes [#51](https://github.com/Rianico/dsh-better-edit/issues/51)
10
+
11
+ ## [0.7.0](https://github.com/Rianico/dsh-better-edit/compare/v0.6.3...v0.7.0) (2026-09-06)
12
+
13
+ ### Features
14
+
15
+ * **session-view:** canon-deficit drift instead of hash rotation (Closes [#46](https://github.com/Rianico/dsh-better-edit/issues/46)) ([#50](https://github.com/Rianico/dsh-better-edit/issues/50)) ([44ba1b3](https://github.com/Rianico/dsh-better-edit/commit/44ba1b3ea3c33759c879363a7e18b4d718edd4d9)), closes [#68](https://github.com/Rianico/dsh-better-edit/issues/68)
16
+ * user/model audience split + glossary error codes ([#49](https://github.com/Rianico/dsh-better-edit/issues/49)) ([1559fc5](https://github.com/Rianico/dsh-better-edit/commit/1559fc5d135d006faa86aa656c166a5e3fa3be08)), closes [#48](https://github.com/Rianico/dsh-better-edit/issues/48) [#45](https://github.com/Rianico/dsh-better-edit/issues/45)
17
+
18
+ ### Bug Fixes
19
+
20
+ * **edit:** Gemma-4 tool-call bleed hardening + prompt channel wording (Closes [#47](https://github.com/Rianico/dsh-better-edit/issues/47)) ([#52](https://github.com/Rianico/dsh-better-edit/issues/52)) ([55e8d21](https://github.com/Rianico/dsh-better-edit/commit/55e8d21bcc57e87ee674c4d7484da0cd200e2e03)), closes [#55](https://github.com/Rianico/dsh-better-edit/issues/55)
21
+ * review follow-ups from 1.6.0 absorb (Closes [#55](https://github.com/Rianico/dsh-better-edit/issues/55)) ([#56](https://github.com/Rianico/dsh-better-edit/issues/56)) ([d6a9cbb](https://github.com/Rianico/dsh-better-edit/commit/d6a9cbb5ae071892dd88aefdaa6b9d875aa091e7))
22
+ * **served:** epoch lifecycle belongs to full reads (Closes [#48](https://github.com/Rianico/dsh-better-edit/issues/48)) ([#54](https://github.com/Rianico/dsh-better-edit/issues/54)) ([959f355](https://github.com/Rianico/dsh-better-edit/commit/959f355b0866a6a892dda2a149cc20c6505fc9ad)), closes [#69](https://github.com/Rianico/dsh-better-edit/issues/69)
23
+ * **served:** refresh canons on truncated serve records (Closes [#53](https://github.com/Rianico/dsh-better-edit/issues/53)) ([#57](https://github.com/Rianico/dsh-better-edit/issues/57)) ([1f8601c](https://github.com/Rianico/dsh-better-edit/commit/1f8601cc8b3608bc79acb82130abbe37990aef75))
24
+
25
+ ### Documentation
26
+
27
+ * **absorb:** record v1.6.0 checkpoint 87a17eb after T1-T4 ([8afba98](https://github.com/Rianico/dsh-better-edit/commit/8afba9842628e44a011c266956d8746725295c11))
28
+ * migrate CLAUDE.md to AGENTS.md with symlink ([4706b6e](https://github.com/Rianico/dsh-better-edit/commit/4706b6e15f6a0ca627059087e3f05953b7b2ae6e))
29
+
1
30
  ## [0.6.3](https://github.com/Rianico/dsh-better-edit/compare/v0.6.2...v0.6.3) (2026-09-05)
2
31
 
3
32
  ### Bug Fixes
package/README.md CHANGED
@@ -28,7 +28,7 @@
28
28
  </p>
29
29
 
30
30
  <p align="center">
31
- <img src="https://img.shields.io/badge/version-0.6.1-blue.svg" alt="Version">
31
+ <img src="https://img.shields.io/badge/version-0.7.0-blue.svg" alt="Version">
32
32
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
33
33
  <img src="https://img.shields.io/badge/DeepSeek_Harness-Plugin-blueviolet.svg" alt="DeepSeek Harness Plugin">
34
34
  <img src="https://img.shields.io/npm/v/dsh-better-edit" alt="npm version">
@@ -56,7 +56,7 @@
56
56
  | --- | --- |
57
57
  | Re-types old code (~5-6× billed) | Two `3-char` hashes, old text never echoed |
58
58
  | One insert shifts every number → silent wrong line | Content addresses — edits above don't move anchors below |
59
- | No check against what was shown | Every line verified; `[E_RANGE_STALE]`/`[E_RANGE_UNSERVED]` reject before write, then **reject-and-serve** returns fresh `HASH│content` |
59
+ | No check against what was shown | Every line verified; `[E_STALE_RANGE]`/`[E_UNSERVED_RANGE]` reject before write, then **reject-and-serve** returns fresh `HASH│content` |
60
60
 
61
61
  > [!TIP]
62
62
  > **Shining points — honest:**
@@ -64,7 +64,7 @@
64
64
  > - **Position-free.** `read 1..5` → `insert @0` → `edit 10..12` still lands at `10..12`. Anchors are `canon(line)` hashes, not positions (ADR-0013). Exterior drift is a notice, not a re-read.
65
65
  > - **Fewer round-trips.** Single-session `1 read → N edits` — no ritual re-reads. Multi-session exterior `A:10..12 / B:20..30` also passes; only overlapping `A∩B≠∅` retries once via `servedRows` (no full `read`). Harness `9/9` green.
66
66
  > - **Fewer tokens.** Compact payload `{path, edits:[[from,to,text]]}` + never echoing `old_string`; diff/echo/rejection rows count as serves. Envelope `-40%` pinned 12-edit corpus, session `-55.8%` on external-drift.
67
- > - **Concurrent-safe, not silent.** `tombstone` per `(session,path)` epoch blocks re-bound `S@3→@3`; `canon` + `hash` + `changed∩[L,R]` makes `pos-free` single-thread and `strict` only on true overlap. One retry vs silent wrong-line.
67
+ > - **Concurrent-safe, not silent.** `retired anchor` per `(session,path)` epoch blocks re-bound `S@3→@3`; `retired` + `canon` + `hash` + `changed∩[L,R]` makes `pos-free` single-thread and `strict` only on true overlap. One retry vs silent wrong-line.
68
68
 
69
69
  Not for one-line touch-ups (near parity) or new files (`write`). Pays off in long sessions and structural edits.
70
70
 
@@ -114,7 +114,7 @@ Returns a diff with fresh anchors — next edit needs no `read`:
114
114
  kQm │ }
115
115
  ```
116
116
 
117
- **Position-free in one line:** `read 1..5` → `insert @0` → `edit 10..12` still verifies `10..12` (`resist` mode). **Multi-session honesty:** `A:10..12+1` shifts `B:20..30→21..31` → `B` passes (drift notice); `B:12..13` overlapping `A` → `E_RANGE_STALE` + fresh rows, one retry.
117
+ **Position-free in one line:** `read 1..5` → `insert @0` → `edit 10..12` still verifies `10..12` (`resist` mode). **Multi-session honesty:** `A:10..12+1` shifts `B:20..30→21..31` → `B` passes (drift notice); `B:12..13` overlapping `A` → `E_STALE_RANGE` + fresh rows, one retry.
118
118
 
119
119
  Batch atomically — one `edit`, up to 32 same-file ranges:
120
120
 
@@ -148,9 +148,9 @@ Env overrides yaml (`DSH_BETTER_EDIT_STORE_DIR`, `DSH_BETTER_EDIT_AUTO_GITIGNORE
148
148
 
149
149
  ## Why Hashline
150
150
 
151
- **Verified against what was served.** Every resolved line checked against `read`/diff/rejection rows. Stale or unseen → `[E_RANGE_STALE]`/`[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]` + fresh `HASH│content`, retry needs no `read`. Session-scoped — sub-agent serves never validate main edits.
151
+ **Verified against what was served.** Every resolved line checked against `read`/diff/rejection rows. Stale or unseen → `[E_STALE_RANGE]`/`[E_UNSERVED_RANGE]` + fresh `HASH│content`, retry needs no `read`. Session-scoped — sub-agent serves never validate main edits.
152
152
 
153
- **Content-addressed.** `canon(line)` strips ASCII whitespace, `xxh32 → 62³=238,328` anchors. Re-inserting identical text keeps its hash; `prettier`/`eslint --fix` between edits doesn't invalidate. Unique by bitset probing — `}`/`import` repeats never collide; cap `238,328` lines (`[E_FILE_TOO_LARGE]`).
153
+ **Content-addressed.** `canon(line)` strips ASCII whitespace, `xxh32 → 62³=238,328` anchors. Re-inserting identical text keeps its hash; `prettier`/`eslint --fix` between edits doesn't invalidate. Unique by bitset probing — `}`/`import` repeats never collide; cap `238,328` lines (`[E_LARGE_FILE]`).
154
154
 
155
155
  **No loop, no ritual.** No-op → `No changes made`; same no-op ×3 → `[E_NOOP_LOOP]`. Diff/echo/rejection rows count as serves — `read` is recovery, not ritual.
156
156
 
@@ -189,13 +189,14 @@ Single stochastic run, `opencode-go/gpt-5.6-luna` high. [Artifact](https://githu
189
189
 
190
190
  | Code | Meaning |
191
191
  | --- | --- |
192
- | `[E_BAD_SHAPE]`/`[E_BAD_REF]` | Bad tuple shape or not bare `3-char` |
193
- | `[E_STALE_ANCHOR]`/`[E_AMBIGUOUS_ANCHOR]` | No line / multi-line → `read` |
194
- | `[E_EDIT_HASH_ECHO]`/`[E_WRITE_HASH_ECHO]` | Copied `HASH│` from same session/path/line — strip and retry |
195
- | `[E_WOULD_EMPTY]`/`[E_NOT_FOUND]`/`[E_ACCESS]`/`[E_NOT_TEXT]`/`[E_FILE_TOO_LARGE]` | Empty guard / missing / access / binary / >238,328 lines |
196
- | `[E_BAD_OP]`/`[E_INVALID_PATCH]`/`[E_BARE_HASH_PREFIX]` | Swapped range / `+HASH│` patch marker (auto-corrected) |
192
+ | `[E_BAD_PAYLOAD]` | Bad tuple shape (payload must be `{path, edits}` with 3-position tuples) |
193
+ | `[E_STALE_ANCHOR]` | No line (hash/retired/canon miss) / multi-line → `read` |
194
+ | `[E_BAD_ANCHOR]` | Not bare `3-char`, or `replacement_text` carries `HASH│`/diff-preview prefixes — refused, remove and retry |
195
+ | `[E_SERVED_ECHO]` | Copied `HASH│` from same session/path/line — refused, remove and retry |
196
+ | `[E_EMPTY_RANGE]`/`[E_NOT_FOUND]`/`[E_ACCESS]`/`[E_UNSUPPORTED_FILE]`/`[E_LARGE_FILE]` | Empty guard / missing / access / binary / >238,328 lines |
197
+ | `[E_REVERSED_ANCHORS]` | Swapped range — healed with dimmed `[USER]` notice on success, otherwise refused |
197
198
  | `[E_BAD_ENCODING]`/`[E_DECODE_FAILED]` | Encoding / decode failed |
198
- | `[E_NOT_OBSERVED]`/`[E_RANGE_STALE]`/`[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]` | Served-state miss — echoed fresh `HASH│content` |
199
+ | `[E_NOT_OBSERVED]`/`[E_STALE_RANGE]`/`[E_UNSERVED_RANGE]` | Served-state miss — echoed fresh `HASH│content` |
199
200
  | `[E_UNDO_STALE]`/`[E_UNDO_UNAVAILABLE]` | Undo stale / unavailable |
200
201
  | `[E_NOOP_LOOP]`/`[E_BATCH_ABORT]` | 3× same no-op / atomic batch fail → nothing written |
201
202
 
@@ -274,7 +275,7 @@ Saved **313 (31%)**. Reproduce: upstream `npm run benchmark`. See [`pi-better-ed
274
275
 
275
276
  ## Roadmap
276
277
 
277
- **Current `0.6.1`:** pos-free `resist`/`strict` + tombstone/canons/epoch, per-session `(session,path)` store, `1222` tests, `9/9` harness.
278
+ **Current `0.7.0`:** pos-free `resist`/`strict` + retired anchor/canons/epoch, per-session `(session,path)` store, `1222` tests, `9/9` harness.
278
279
 
279
280
  <details><summary>Next</summary>
280
281
 
package/lib/constants.js CHANGED
@@ -10,5 +10,9 @@ export const BATCH_EDIT_MAX_ITEMS = EDITS_MAX_ITEMS;
10
10
  export const SERVED_TTL_MS = 7 * 24 * 60 * 60 * 1000;
11
11
  export const SERVED_ECHO_CAP = 150;
12
12
  export const NOOP_LOOP_THRESHOLD = 3;
13
- export const NEW_CONTENT_NOT_STRING_MSG = `[E_BAD_SHAPE] "replacement_text" must be a string with \\n line separators, not an array.` +
13
+ export const NEW_CONTENT_NOT_STRING_MSG = `[MODEL] [E_BAD_PAYLOAD] "replacement_text" must be a string with \\n line separators, not an array.` +
14
14
  ` Do not pass an array of lines — pass the replacement text as one string: "line1\\nline2". Use "" to delete a range.`;
15
+ export function eLargeFileMsg(displayPath, lineCount, maxLines) {
16
+ return `[MODEL] [E_LARGE_FILE] ${displayPath} has ${lineCount} lines, exceeding the ${maxLines}-line edit limit. Hashline editing targets source-sized files; for very large files use write or a non-line-based approach.`;
17
+ }
18
+ export const E_ANCHOR_SPACE_EXHAUSTED_WARNING = "[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted";
package/lib/contract.js CHANGED
@@ -2,14 +2,14 @@
2
2
  * One module owns the request shapes for the hashline tools — edit,
3
3
  * read, undo_last_edit — plus their validation. Field sets are
4
4
  * declared once here; every tool validates through these asserts, and the
5
- * [E_BAD_SHAPE] vocabulary is shared instead of re-implemented per tool.
5
+ * [E_BAD_PAYLOAD] vocabulary is shared instead of re-implemented per tool.
6
6
  *
7
7
  * Contract now mirrors upstream ADR-0007: {path: string|null, edits: [[remove_from,remove_to,replacement_text],...]} tuple payload,
8
8
  * single-file, atomic. batch_edit is removed.
9
9
  * @module dsh-better-edit/contract
10
10
  */
11
11
  import { EDITS_MAX_ITEMS } from "./constants.js";
12
- import { isRec, normalizeFilePath, rejectUnknownFields } from "./utils.js";
12
+ import { isRec, normalizeFilePath, rejectUnknownFields, CodedError } from "./utils.js";
13
13
  // ---- normalized marker -----------------------------------------------------
14
14
  export const normalizedEdit = Symbol("normalizedEdit");
15
15
  export function isNormalizedEdit(input) {
@@ -33,7 +33,16 @@ export function editRequestFrom(input) {
33
33
  // but handle here for direct calls
34
34
  }
35
35
  const { path, edits } = rec;
36
- if (path !== null && (typeof path !== "string" || path.length === 0))
36
+ // Gemma-4 tool-call bleed (#55): the model may wrap the path in <|>, │, |,
37
+ // quotes, or backticks after seeing │ separators. Strip wrappers iteratively.
38
+ let effectivePath = path;
39
+ if (typeof effectivePath === "string") {
40
+ const sanitized = sanitizePath(effectivePath);
41
+ if (sanitized === null)
42
+ return undefined;
43
+ effectivePath = sanitized;
44
+ }
45
+ if (effectivePath !== null && (typeof effectivePath !== "string" || effectivePath.length === 0))
37
46
  return undefined;
38
47
  if (!Array.isArray(edits) || edits.length === 0)
39
48
  return undefined;
@@ -44,7 +53,47 @@ export function editRequestFrom(input) {
44
53
  return undefined;
45
54
  items.push(normalized);
46
55
  }
47
- return { path: path, edits: items };
56
+ return { path: effectivePath, edits: items };
57
+ }
58
+ /**
59
+ * Strip Gemma-4 tool-call bleed wrappers from a path string: `<|>`, `\u2502`, `|`
60
+ * pairs plus surrounding quotes/backticks, applied iteratively. Returns the
61
+ * cleaned path, or null when nothing usable remains (caller rejects).
62
+ */
63
+ /** Paired/single bleed wrappers, longest-token first. Each entry strips one layer. */
64
+ const PATH_WRAPPERS = [
65
+ { open: "<|>", close: "<|>", minLen: 6, pairOnly: false },
66
+ { open: "\u2502", close: "\u2502", minLen: 2, pairOnly: true },
67
+ { open: "|", close: "|", minLen: 2, pairOnly: true },
68
+ { open: '"', close: '"', minLen: 0, pairOnly: true },
69
+ { open: "'", close: "'", minLen: 0, pairOnly: true },
70
+ { open: "`", close: "`", minLen: 0, pairOnly: true },
71
+ ];
72
+ export function sanitizePath(value) {
73
+ if (typeof value !== "string")
74
+ return null;
75
+ let cleaned = value.trim();
76
+ let changed = true;
77
+ while (changed) {
78
+ changed = false;
79
+ for (const w of PATH_WRAPPERS) {
80
+ if (cleaned.length > w.minLen && cleaned.startsWith(w.open) && cleaned.endsWith(w.close)) {
81
+ cleaned = cleaned.slice(w.open.length, -w.close.length).trim();
82
+ changed = true;
83
+ }
84
+ else if (!w.pairOnly) {
85
+ if (cleaned.startsWith(w.open)) {
86
+ cleaned = cleaned.slice(w.open.length).trim();
87
+ changed = true;
88
+ }
89
+ else if (cleaned.endsWith(w.close)) {
90
+ cleaned = cleaned.slice(0, -w.close.length).trim();
91
+ changed = true;
92
+ }
93
+ }
94
+ }
95
+ }
96
+ return cleaned.length > 0 ? cleaned : null;
48
97
  }
49
98
  export const EDIT_TUPLE_HINT = "Edit must be called with exactly one payload. Use the canonical payload " +
50
99
  '{"path": path, "edits": [[remove_from, remove_to, replacement_text], ...]}: ' +
@@ -99,49 +148,49 @@ export function prepareEditArguments(args) {
99
148
  if (valid) {
100
149
  return { path: valid.path, edits: args.edits };
101
150
  }
102
- throw new Error(`[E_BAD_SHAPE] ${EDIT_TUPLE_HINT} ${describeReceived(args)}`);
151
+ throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] ${EDIT_TUPLE_HINT} ${describeReceived(args)}`);
103
152
  }
104
153
  // ---- assertions ---------------------------------------------------------------
105
154
  export function assertEditRequest(request) {
106
155
  if (!isNormalizedEdit(request)) {
107
- throw new Error("[E_BAD_SHAPE] Edit request must be exactly { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
156
+ throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] Edit request must be exactly { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
108
157
  }
109
158
  rejectUnknownFields(request, EDIT_KS, "Edit request");
110
159
  const req = request;
111
160
  if (req.path !== null && (typeof req.path !== "string" || req.path.length === 0)) {
112
- throw new Error('[E_BAD_SHAPE] Edit request path must be a non-empty string or null.');
161
+ throw new CodedError("E_BAD_PAYLOAD", '[MODEL] [E_BAD_PAYLOAD] Edit request path must be a non-empty string or null.');
113
162
  }
114
163
  if (!Array.isArray(req.edits) || req.edits.length === 0) {
115
- throw new Error('[E_BAD_SHAPE] Edit request requires a non-empty "edits" array.');
164
+ throw new CodedError("E_BAD_PAYLOAD", '[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "edits" array.');
116
165
  }
117
166
  if (req.edits.length > EDITS_MAX_ITEMS) {
118
- throw new Error(`[E_BAD_SHAPE] edit accepts at most ${EDITS_MAX_ITEMS} edits; got ${req.edits.length}. Split the batch.`);
167
+ throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] edit accepts at most ${EDITS_MAX_ITEMS} edits; got ${req.edits.length}. Split the batch.`);
119
168
  }
120
169
  for (let index = 0; index < req.edits.length; index++) {
121
170
  const item = req.edits[index];
122
171
  if (typeof item.remove_from !== "string" || typeof item.remove_to !== "string" || typeof item.replacement_text !== "string") {
123
- throw new Error(`[E_BAD_SHAPE] Edit request edits[${index}] must be a three-position array [remove_from, remove_to, replacement_text].`);
172
+ throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Edit request edits[${index}] must be a three-position array [remove_from, remove_to, replacement_text].`);
124
173
  }
125
174
  }
126
175
  }
127
176
  // legacy — now always fails with new shape message (batch_edit removed)
128
177
  export function assertBatchEditRequest(_request) {
129
- throw new Error("[E_BAD_SHAPE] batch_edit has been removed. Use edit with { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
178
+ throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] batch_edit has been removed. Use edit with { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
130
179
  }
131
180
  export function assertReadRequest(request) {
132
181
  if (!isRec(request))
133
- throw new Error("[E_BAD_SHAPE] Read request must be an object.");
182
+ throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] Read request must be an object.");
134
183
  rejectUnknownFields(request, READ_KS, "Read request");
135
184
  if (typeof request.path !== "string" || request.path.length === 0) {
136
- throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
185
+ throw new CodedError("E_BAD_PAYLOAD", '[MODEL] [E_BAD_PAYLOAD] Read request requires a non-empty "path" string.');
137
186
  }
138
187
  }
139
188
  export function assertUndoRequest(request) {
140
189
  if (!isRec(request))
141
- throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
190
+ throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] undo_last_edit request must be an object.");
142
191
  normalizeFilePath(request);
143
192
  if (typeof request.path !== "string" || request.path.length === 0) {
144
- throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
193
+ throw new CodedError("E_BAD_PAYLOAD", '[MODEL] [E_BAD_PAYLOAD] undo_last_edit request requires a non-empty "path" string.');
145
194
  }
146
195
  }
147
196
  // ---- shared JSON Schema literals (co-located with field sets) ---------------
@@ -23,8 +23,7 @@ export function buildMetrics(args) {
23
23
  return metrics;
24
24
  }
25
25
  export function finalizeResult(input) {
26
- const modelWarnings = input.warnings?.filter((w) => !w.startsWith("Batch drift note:"));
27
- const base = input.diff + warnBlock(modelWarnings);
26
+ const base = input.diff + warnBlock(input.warnings);
28
27
  return base;
29
28
  }
30
29
  export function finalizeToolResult(details) {
@@ -63,8 +62,7 @@ export function buildNoop(input) {
63
62
  const noopDetailsText = noopEdit
64
63
  ? `Edit for ${noopEdit.loc} is identical to current content:\n ${noopEdit.loc}: ${clipLine(noopEdit.currentContent)}`
65
64
  : "The edit produced identical content.";
66
- const modelWarnings = warnings?.filter((w) => !w.startsWith("Batch drift note:"));
67
- const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(modelWarnings)}`;
65
+ const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(warnings)}`;
68
66
  const metrics = buildMetrics({
69
67
  classification: "noop",
70
68
  editsAttempted: editMeta.editsAttempted,
@@ -90,8 +88,7 @@ export function buildChanged(input) {
90
88
  const diffResult = genDiff(originalNormalized, result, 1, resultHashes, originalHashes);
91
89
  const addedLines = editMeta.addedLines;
92
90
  const removedLines = editMeta.removedLines;
93
- const modelWarnings = warnings?.filter((w) => !w.startsWith("Batch drift note:"));
94
- const warningsBlock = warnBlock(modelWarnings);
91
+ const warningsBlock = warnBlock(warnings);
95
92
  const successPrefix = `Successfully edited in ${path}.`;
96
93
  const lineSummary = addedLines > 0 || removedLines > 0
97
94
  ? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
@@ -144,8 +141,7 @@ export function buildBatchResult(sections) {
144
141
  .filter((d) => d !== undefined)
145
142
  .join("\n\n");
146
143
  if (allNoop) {
147
- const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
148
- const text = `No changes made. All ${totalEdits} edit(s) in the batch produced identical content.\nClassification: noop${warnBlock(modelWarnings)}`;
144
+ const text = `No changes made. All ${totalEdits} edit(s) in the batch produced identical content.\nClassification: noop${warnBlock(warnings)}`;
149
145
  return {
150
146
  content: [{ type: "text", text }],
151
147
  details: {
@@ -180,8 +176,7 @@ export function buildBatchResult(sections) {
180
176
  ? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
181
177
  : "";
182
178
  const summary = `Successfully edited ${appliedFiles.length} file(s) — ${appliedTotal} of ${totalEdits} edit(s) applied${noopTotal > 0 ? ` (${noopTotal} noop)` : ""}.${lineSummary}`;
183
- const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
184
- const baseText = `${summary}${warnBlock(modelWarnings)}`;
179
+ const baseText = `${summary}${warnBlock(warnings)}`;
185
180
  const diffSection = formatDiffCard(diff);
186
181
  const text = `${baseText}${diffSection}`;
187
182
  return {
package/lib/encoding.js CHANGED
@@ -248,7 +248,7 @@ export async function detectWithChardet(bytes, allowlist) {
248
248
  }
249
249
  }
250
250
  /**
251
- * Chardet-based Top-3 for E_NOT_TEXT (primary) and autoGuess.
251
+ * Chardet-based Top-3 for E_UNSUPPORTED_FILE (primary) and autoGuess.
252
252
  * Returns chardet candidates filtered by allowlist and decodable, else empty.
253
253
  */
254
254
  export async function chardetTop3Candidates(bytes, allowlist) {
@@ -53,7 +53,7 @@ export function invalidateIfStale(targetKey, currentVersion) {
53
53
  // ---------------------------------------------------------------------------
54
54
  export function buildTop3ErrorMessage(displayPath, candidates) {
55
55
  const candStr = candidates.map((c) => `${c.encoding}("${c.sample.slice(0, 20).replace(/"/g, "'")}")`).join(", ");
56
- return `[E_NOT_TEXT] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files. Top-3 guesses: ${candStr}. Try read({encoding: "<encoding>"}) or set DSH_BETTER_EDIT_AUTO_GUESS_ENCODING=true to auto-decode.`;
56
+ return `[MODEL] [E_UNSUPPORTED_FILE] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files. Top-3 guesses: ${candStr}. Try read({encoding: "<encoding>"}) or set DSH_BETTER_EDIT_AUTO_GUESS_ENCODING=true to auto-decode.`;
57
57
  }
58
58
  function buildAutoGuessFooterFromCandidates(candidates) {
59
59
  // chardet path vs heuristic path share same footer shape, just score vs confidence
@@ -76,7 +76,7 @@ function isMidConfidenceHeuristic(best, second) {
76
76
  /**
77
77
  * Deterministic admission for a raw byte buffer. No IO, no side effects
78
78
  * except Top-3 scoring. Caller owns recording the returned state via
79
- * `recordOpenState` and handling the footer vs E_NOT_TEXT split.
79
+ * `recordOpenState` and handling the footer vs E_UNSUPPORTED_FILE split.
80
80
  *
81
81
  * Order is fixed: BOM sniff always precedes strict UTF-8, which always
82
82
  * precedes guessing. Probabilistic encodings are last resort, gated by
@@ -196,9 +196,9 @@ export async function decodeForOpen(bytes, config, opts = {}) {
196
196
  };
197
197
  }
198
198
  }
199
- // No candidate succeeded — fall through to E_NOT_TEXT with Top-3
199
+ // No candidate succeeded — fall through to E_UNSUPPORTED_FILE with Top-3
200
200
  }
201
- // 5) E_NOT_TEXT + Top-3 always pushed (even when autoGuess off)
201
+ // 5) E_UNSUPPORTED_FILE + Top-3 always pushed (even when autoGuess off)
202
202
  // Use chardet Top-3 when available, else heuristic Top-3 — same as fs-bridge fallback
203
203
  let candidates = [];
204
204
  try {
package/lib/file-view.js CHANGED
@@ -21,7 +21,7 @@ import { constants } from "node:fs";
21
21
  import { open as fsOpen, stat as fsStat } from "fs/promises";
22
22
  import { access as fsAccess } from "fs/promises";
23
23
  import { fileTypeFromBuffer } from "file-type";
24
- import { SNIFF_BYTES, MAX_BYTES, MAX_READ_LINE_BYTES } from "./constants.js";
24
+ import { SNIFF_BYTES, MAX_BYTES, MAX_READ_LINE_BYTES, eLargeFileMsg } from "./constants.js";
25
25
  import { lineHashes, fmtRegion, HASH_SEP } from "./hashline/index.js";
26
26
  import { HASH_SPACE } from "./hashline/hash-assign.js";
27
27
  import { visLines, abortIf, errCode } from "./utils.js";
@@ -206,7 +206,7 @@ export async function loadFileKindAndText(filePath, options) {
206
206
  newlineCount++;
207
207
  }
208
208
  if (newlineCount > options.maxLines) {
209
- throw new Error(`[E_FILE_TOO_LARGE] ${options.displayPath ?? filePath} has more than ${options.maxLines} lines, exceeding the ${options.maxLines}-line edit limit. Hashline editing targets source-sized files; for very large files use write or a non-line-based approach.`);
209
+ throw new Error(eLargeFileMsg(options.displayPath ?? filePath, newlineCount, options.maxLines));
210
210
  }
211
211
  }
212
212
  return decoded;
@@ -241,27 +241,27 @@ export async function valAccess(absolutePath, path, accessMode = constants.R_OK)
241
241
  catch (error) {
242
242
  const code = errCode(error);
243
243
  if (code === "ENOENT") {
244
- throw new Error(`[E_NOT_FOUND] File not found: ${path}`);
244
+ throw new Error(`[MODEL] [E_NOT_FOUND] File not found: ${path}`);
245
245
  }
246
246
  if (code === "EACCES" || code === "EPERM") {
247
247
  const accessLabel = accessMode & constants.W_OK ? "not writable" : "not readable";
248
- throw new Error(`[E_ACCESS] File is ${accessLabel}: ${path}`);
248
+ throw new Error(`[MODEL] [E_ACCESS] File is ${accessLabel}: ${path}`);
249
249
  }
250
250
  if (code === "ELOOP") {
251
- throw new Error(`[E_ACCESS] Too many symbolic links while resolving: ${path}`);
251
+ throw new Error(`[MODEL] [E_ACCESS] Too many symbolic links while resolving: ${path}`);
252
252
  }
253
- throw new Error(`[E_ACCESS] Cannot access file: ${path}`);
253
+ throw new Error(`[MODEL] [E_ACCESS] Cannot access file: ${path}`);
254
254
  }
255
255
  }
256
256
  export function valKind(file, path) {
257
257
  if (file.kind === "directory") {
258
- throw new Error(`[E_NOT_TEXT] Path is a directory: ${path}. Use ls to inspect directories.`);
258
+ throw new Error(`[MODEL] [E_UNSUPPORTED_FILE] Path is a directory: ${path}.`);
259
259
  }
260
260
  if (file.kind === "binary") {
261
- throw new Error(`[E_NOT_TEXT] Path is a binary file: ${path} (${file.description}). Hashline edit only supports text files.`);
261
+ throw new Error(`[MODEL] [E_UNSUPPORTED_FILE] Path is a binary file: ${path} (${file.description}). Hashline edit only supports text files.`);
262
262
  }
263
263
  if (file.kind === "image") {
264
- throw new Error(`[E_NOT_TEXT] Path is an image file: ${path}. Hashline edit only supports text files.`);
264
+ throw new Error(`[MODEL] [E_UNSUPPORTED_FILE] Path is an image file: ${path}. Hashline edit only supports text files.`);
265
265
  }
266
266
  }
267
267
  function fmtSnapId(canonicalPath, info) {
@@ -287,10 +287,10 @@ export async function normFromText(input) {
287
287
  if (input.maxLines !== undefined) {
288
288
  const lineCount = visLines(normalized).length;
289
289
  if (lineCount > input.maxLines) {
290
- throw new Error(`[E_FILE_TOO_LARGE] ${displayPath} has ${lineCount} lines, exceeding the ${input.maxLines}-line edit limit. Hashline editing targets source-sized files; for very large files use write or a non-line-based approach.`);
290
+ throw new Error(eLargeFileMsg(displayPath, lineCount, input.maxLines));
291
291
  }
292
292
  }
293
- const fileHashes = await lineHashes(normalized, absolutePath, undefined, input.store, input.noPersist !== true, input.reservedHashes, input.retiredHashes);
293
+ const fileHashes = await lineHashes(normalized, absolutePath, input.previous, input.store, input.noPersist !== true, input.reservedHashes, input.retiredHashes);
294
294
  return {
295
295
  absolutePath,
296
296
  normalized,
@@ -325,6 +325,7 @@ export async function readNormFile(path, cwd, options) {
325
325
  reservedHashes: options?.reservedHashes,
326
326
  retiredHashes: options?.retiredHashes,
327
327
  hadUtf8DecodeErrors: file.hadUtf8DecodeErrors,
328
+ previous: options?.previous,
328
329
  });
329
330
  }
330
331
  // --- Read render (from read-render.ts, private) ---
@@ -332,7 +333,7 @@ function normPosInt(value, name) {
332
333
  if (value === undefined)
333
334
  return undefined;
334
335
  if (!Number.isInteger(value) || value < 1) {
335
- throw new Error(`[E_BAD_SHAPE] Read request field "${name}" must be a positive integer.`);
336
+ throw new Error(`[MODEL] [E_BAD_PAYLOAD] Read request field "${name}" must be a positive integer.`);
336
337
  }
337
338
  return value;
338
339
  }
@@ -473,6 +474,7 @@ export async function readView(io, path, cwd, opts = {}) {
473
474
  maxLines: MAX_HASH_LINES,
474
475
  reservedHashes: opts.reservedHashes,
475
476
  retiredHashes: opts.retiredHashes,
477
+ previous: opts.previous,
476
478
  });
477
479
  const r = await fmtReadPreview(normalized, { offset: opts.offset, limit: opts.limit }, fileHashes, absolutePath);
478
480
  return {
package/lib/fs-bridge.js CHANGED
@@ -20,6 +20,7 @@ import { loadConfig } from "./store-config.js";
20
20
  import { fileSnap } from "./file-reader.js";
21
21
  import { resolveTarget, toCwd } from "./paths.js";
22
22
  import { decodeForOpen, recordOpenState, recordFooter, getEncodingState as _getEncodingState, setEncodingState as _setEncodingState, clearEncodingState as _clearEncodingState, getAutoGuessFooter as _getAutoGuessFooter, setAutoGuessFooter as _setAutoGuessFooter, clearAutoGuessFooter as _clearAutoGuessFooter, invalidateIfStale, prepareForSave, } from "./file-encoding-state.js";
23
+ import { codeOf } from "./utils.js";
23
24
  export { _getEncodingState as getEncodingState, _setEncodingState as setEncodingState, _clearEncodingState as clearEncodingState, _getAutoGuessFooter as getAutoGuessFooter, _setAutoGuessFooter as setAutoGuessFooter, _clearAutoGuessFooter as clearAutoGuessFooter, };
24
25
  // Keep alias for tests that import getAutoGuessFooter via fs-bridge
25
26
  export function getAutoGuessFooterCompat(k) {
@@ -37,13 +38,13 @@ export function mapFsError(error, displayPath) {
37
38
  typeof error.code === "string") {
38
39
  const code = error.code;
39
40
  if (code === "FS_NOT_FOUND") {
40
- throw new Error(`[E_NOT_FOUND] File not found: ${displayPath}`);
41
+ throw new Error(`[MODEL] [E_NOT_FOUND] File not found: ${displayPath}`);
41
42
  }
42
43
  if (code === "FS_PERMISSION_DENIED") {
43
- throw new Error(`[E_ACCESS] Cannot access file: ${displayPath}`);
44
+ throw new Error(`[MODEL] [E_ACCESS] Cannot access file: ${displayPath}`);
44
45
  }
45
46
  if (code === "FS_NOT_TEXT" || code === "FS_NOT_REGULAR_FILE") {
46
- throw new Error(`[E_NOT_TEXT] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files. Try read({encoding: "gbk"}) or enable autoGuessEncoding.`);
47
+ throw new Error(`[MODEL] [E_UNSUPPORTED_FILE] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files. Try read({encoding: "gbk"}) or enable autoGuessEncoding.`);
47
48
  }
48
49
  if (code === "FS_BAD_ENCODING") {
49
50
  throw new Error(`[E_BAD_ENCODING] Unknown encoding for ${displayPath}. Supported: utf8, gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1`);
@@ -52,7 +53,7 @@ export function mapFsError(error, displayPath) {
52
53
  throw new Error(`[E_DECODE_FAILED] Bytes in ${displayPath} cannot be decoded with requested encoding.`);
53
54
  }
54
55
  if (code === "FS_STALE_VERSION") {
55
- throw new Error(`[E_RANGE_STALE] The file changed on disk since it was read (version guard rejected the write). Call read() to get fresh anchors, then retry.`);
56
+ throw new Error(`[MODEL] [E_STALE_RANGE] The file changed on disk since it was read (version guard rejected the write). Call read() to get fresh anchors, then retry.`);
56
57
  }
57
58
  if (code === "FS_NOT_OBSERVED") {
58
59
  throw new Error(`[E_NOT_OBSERVED] The file has not been observed in this session (read-before-write policy). Call read() first, then retry the edit.`);
@@ -254,7 +255,7 @@ export function localIO() {
254
255
  recordFooter(absolutePath, decoded.footer);
255
256
  return decoded.text;
256
257
  }
257
- // Deterministic path via seam, with local fallback for E_NOT_TEXT when autoGuess off
258
+ // Deterministic path via seam, with local fallback for E_UNSUPPORTED_FILE when autoGuess off
258
259
  try {
259
260
  const bytes = await readFile(absolutePath);
260
261
  const cfgL = loadConfig();
@@ -266,8 +267,8 @@ export function localIO() {
266
267
  return decoded.text;
267
268
  }
268
269
  catch (error) {
269
- // Local fallback: when autoGuess off, E_NOT_TEXT should fall back to raw UTF-8 with � (no throw)
270
- if (error instanceof Error && error.message.includes("[E_NOT_TEXT]")) {
270
+ // Local fallback: when autoGuess off, E_UNSUPPORTED_FILE should fall back to raw UTF-8 with � (no throw)
271
+ if (codeOf(error) === "E_UNSUPPORTED_FILE") {
271
272
  return readFile(absolutePath, "utf-8");
272
273
  }
273
274
  throw error;