dsh-better-edit 1.2.3 → 1.2.4

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
@@ -11,6 +11,20 @@ All notable changes to this project will be documented in this file.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.2.4] - 2026-11-17
15
+
16
+ ### Tests
17
+
18
+ * **edit:** pin the applied-vs-rejection notice tier (#115) (#121)
19
+
20
+ ### Bug Fixes
21
+
22
+ * **edit:** reject an unnamed file at admission instead of guessing it from anchors (#117) (#120)
23
+ * **domain-errors:** route `W_NOOP` to `MODEL` so the second identical no-op carries "Resend will reject" to the model that would resend, not a human-only `[USER]` notice — warnings are now guarded by an audience oracle that refuses model-directed text on a `USER` warning (ADR-0014 amendment) (#122)
24
+ * **install:** gate the hashline tools on the composed preset's own tool policy — `read` stays unconditional, while `edit`, `str_replace_editor`, `undo_last_edit` and the write hook follow the preset's layer, and self-heal heals exactly the installed set; ADR-0032 records the async scope seam and the fail-open fallback (#110) (#125)
25
+ * **edit-undo:** restore the pre-edit anchor strings on undo — the restore reuses the pre-edit assignment, revives it, and retires the superseded post-edit anchors in the same store unit, reversing ADR-0017's named deviation (#111) (#126)
26
+ * **encoding:** consume the encoding recorded by `read({ encoding })` in every mutating read, and refuse a write the text seam cannot reproduce byte-faithfully with the typed `E_ENCODING_UNWRITABLE` instead of transcoding silently; ADR-0012 amended (#112) (#127)
27
+
14
28
  ## [1.2.3] - 2026-11-16
15
29
 
16
30
  ### Bug Fixes
package/README.md CHANGED
@@ -210,31 +210,50 @@ Single stochastic run, `opencode-go/gpt-5.6-luna` high. [Artifact](https://githu
210
210
 
211
211
  ## Tools
212
212
 
213
- | Tool | What it does |
214
- | ---------------- | ----------------------------------------------------------------------------------------------------------- |
215
- | `read` | `HASH│content` with `offset`/`limit`; `[Showing N-M of T]` paging; `>200KB` lines show marker |
216
- | `read_skill` | Plain text, no hashes, no serves — editing after it needs a serve |
217
- | `edit` | `{path, edits:[[from,to,text]]}` `path:string\|null` inference, `""` deletes, atomic ≤32, verify-then-write |
218
- | `undo_last_edit` | `{path}` restores last edit (BOM/line endings/anchors), persisted |
213
+ | Tool | What it does |
214
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
215
+ | `read` | `HASH│content` with `offset`/`limit`; `[Showing N-M of T]` paging; `>200KB` lines show marker |
216
+ | `read_skill` | Plain text, no hashes, no serves — editing after it needs a serve |
217
+ | `edit` | `{file, edits:[[from,to,text]]}` (named objects too; `path`/`file_path` aliases fold), `""` deletes, atomic ≤32, verify-then-write |
218
+ | `undo_last_edit` | `{path}` restores last edit (BOM/line endings/anchors), persisted |
219
219
 
220
220
  `write` stays, but refuses an exact `HASH│` echo for same `session/path/line` before dispatch.
221
221
 
222
222
  ### Error codes
223
223
 
224
- | Code | Meaning |
225
- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
226
- | `[E_BAD_PAYLOAD]` | Bad tuple shape (payload must be `{path, edits}` with 3-position tuples) |
227
- | `[E_STALE_ANCHOR]` | No line (hash/retired/canon miss) / multi-line → `read` |
228
- | `[E_BAD_ANCHOR]` | Not bare `3-char`, or `replacement_text` carries `HASH│`/diff-preview prefixes — refused, remove and retry |
229
- | `[E_SERVED_ECHO]` | Copied `HASH│` from same session/path/line — refused, remove and retry |
230
- | `[E_EMPTY_RANGE]`/`[E_NOT_FOUND]`/`[E_ACCESS]`/`[E_UNSUPPORTED_FILE]`/`[E_LARGE_FILE]` | Empty guard / missing / access / binary / >238,328 lines |
231
- | `[E_REVERSED_ANCHORS]` | Swapped range — healed with dimmed `[USER]` notice on success, otherwise refused |
232
- | `[E_BAD_ENCODING]`/`[E_DECODE_FAILED]` | Encoding / decode failed |
233
- | `[E_NOT_OBSERVED]`/`[E_STALE_RANGE]`/`[E_UNSERVED_RANGE]` | Served-state miss — echoed fresh `HASH│content` |
234
- | `[E_UNDO_STALE]`/`[E_UNDO_UNAVAILABLE]` | Undo stale / unavailable |
235
- | `[E_NOOP_LOOP]`/`[E_BATCH_ABORT]` | 3× same no-op / atomic batch fail → nothing written |
236
-
237
- Full list in `src/` — every rejection echoes fresh rows, no `read` needed.
224
+ | Code | Meaning | What to do |
225
+ | ------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
226
+ | `[E_BAD_PAYLOAD]` | Request shape is wrong (unknown field, missing `file`, bad tuple) | Fix the shape and resend |
227
+ | `[E_MALFORMED_ANCHOR]` | The anchor token is not a bare 3-char anchor (pasted block or pseudo-anchor) | Pass the bare anchor and retry |
228
+ | `[E_UNKNOWN_ANCHOR]` | The anchor was never served for this file | `read` the file for fresh anchors |
229
+ | `[E_FOREIGN_ANCHOR]` | The anchor belongs to another file or session | Use anchors served for this file |
230
+ | `[E_STALE_ANCHOR]` | The anchor no longer resolves (hash / retired / canon miss) | `read` for fresh anchors |
231
+ | `[E_AMBIGUOUS_MATCH]` | `str_replace` `old_str` matches more than once | Narrow `old_str` |
232
+ | `[E_NO_MATCH]` | `str_replace` `old_str` is absent | Re-`view` and retry |
233
+ | `[E_EMPTY_RANGE]` | The edit would empty a non-empty file | Use `write` |
234
+ | `[E_STALE_RANGE]` | The served range changed on disk | Apply the echoed fresh rows |
235
+ | `[E_UNSERVED_RANGE]` | The range contains lines that were never served | `read` that range |
236
+ | `[E_UNVERIFIED_RANGE]` | A boundary anchor could not be verified against served state | `read` and retry |
237
+ | `[E_SUSPICIOUS_TEXT]` | Replacement text carries copied `HASH│` or diff-preview markers | Remove them and resend |
238
+ | `[E_BLIND_REPLACE]` | `write` / `str_replace_editor` ran before the file was observed | `read` / `view` first |
239
+ | `[E_TARGET_LOST]` | The target vanished or changed identity mid-operation | `read` and re-target |
240
+ | `[E_BATCH_ABORT]` | One item failed; nothing was written | Fix the item and resend the batch |
241
+ | `[E_NOOP_LOOP]` | The same no-op edit was resubmitted | Change the edit |
242
+ | `[E_ACCESS]` | The path is not readable or writable | Fix the permission |
243
+ | `[E_NOT_FOUND]` | No such file | Check the parent directory |
244
+ | `[E_FILE_EXISTS]` | A `create` target already exists | Choose a new path |
245
+ | `[E_UNSUPPORTED_FILE]` | Directory, binary, or non-text file | Choose a text file |
246
+ | `[E_ENCODING_UNWRITABLE]` | The recorded encoding cannot be reproduced by a UTF-8 text write | Set `normalizeToUtf8: true` to migrate, or edit the file outside the plugin |
247
+ | `[E_UNSUPPORTED]` | `str_replace_editor undo_edit` is not implemented | Use `undo_last_edit` |
248
+ | `[E_BAD_COMMAND]` | Unknown `str_replace_editor` command | Use `view`, `str_replace`, `insert`, or `create` |
249
+ | `[E_LARGE_FILE]` | Above the line or anchor-space limit | Use `write` or split the file |
250
+ | `[E_UNDO_STALE]` | The file changed after the edit | No undo; re-read |
251
+ | `[E_UNDO_UNAVAILABLE]` | Undo history could not be persisted | Retry the edit |
252
+ | `[E_UNDO_NOT_RECORDED]` | The revert landed but the store could not record it | Re-read; the next undo clears the stale history |
253
+ | `[E_STORE_NEWER_VERSION]` | The store was written by a newer plugin version | Upgrade the plugin, or point the store elsewhere |
254
+ | `[E_UNKNOWN]` | Unexpected internal error | Report it; the message is preserved |
255
+
256
+ `ERROR_REGISTRY` in `src/domain-errors.ts` is the source of truth for this table; `test/arch/error-table-vocabulary.test.ts` fails when the two disagree.
238
257
 
239
258
  ## Comparison
240
259
 
package/README.zh.md CHANGED
@@ -58,7 +58,7 @@ Hashline 用两个哈希代替旧文本——**编辑 token 减少 31%**(多
58
58
  > - **自愈而非静默。** 外部编辑永不被覆盖——过期范围被拒绝并以全新 `HASH│content` 重发重试;孤儿 served 条目无需全量重读即可自愈(ADR-0008)。Fail-closed,而非自动合并。
59
59
  > - **格式化容忍。** ASCII 空白不敏感锚点在 `prettier`/`black`/`eslint --fix` 之间存活(`formatOnSave`、监听、CI)。仅限 linter 场景——字符串内的空白不区分(ADR-0005)。
60
60
  > - **链式与批量,无重读仪式。** 未受影响行的锚点保持有效;diff/回显/拒绝行即视为已提供。`edit` 最多 32 个同文件编辑原子执行(`[E_BATCH_ABORT]`),相比 `str_replace` 信封约 -40%。
61
- > - **读守卫。** 从未展示过的行永不被编辑——`[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]`/`[E_STALE_ANCHOR]` 在写入前拒绝,随后 `reject-and-serve`。
61
+ > - **读守卫。** 从未展示过的行永不被编辑——`[E_UNSERVED_RANGE]`/`[E_UNVERIFIED_RANGE]`/`[E_STALE_ANCHOR]` 在写入前拒绝,随后 `reject-and-serve`。
62
62
  > - **更少往返。** 实测:同样外部漂移重构,OMP 封装需 6 次调用,hashline 仅 3 次;信封 vs `str_replace` 的节省是稳定值—— upstream 电池可复现(算法相同)。
63
63
 
64
64
  不适用于单行小改动(接近持平)或新建文件(用 `write`)。它的价值在长会话与结构性编辑中体现——任何不允许改错行的场景。
@@ -225,8 +225,8 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
225
225
  | 错误地址(锚点/行号差一行) | **不可能**——锚点解析到具体行;解析出的每一行都对照已提供状态校验,在**写入任何内容之前**被拒绝 | **可能**——当前标签下的错误行号会**悄悄**落到错误位置;标签只证明文件版本,从不证明行 |
226
226
  | 模型查看后文件在磁盘上被改动 | 硬拒绝 + 回传新锚点(reject-and-serve);重试无需 `read` | 标签不匹配 → 拒绝**或**对未知的当前内容做尽力而为的三方合并 |
227
227
  | 上方编辑导致文件移位 | 什么都不移位——锚点是内容地址;diff 提供新锚点 | **每次编辑都重新编号**——“RE-GROUND AFTER EVERY EDIT” 是它自己的头号规则;账由模型记 |
228
- | 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_AMBIGUOUS_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
229
- | 从未展示给模型的行 | `[E_RANGE_UNSERVED]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
228
+ | 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_STALE_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
229
+ | 从未展示给模型的行 | `[E_UNSERVED_RANGE]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
230
230
  | 表达式中间 / 错误的块节点 | 无关——任何已校验的行范围都合法 | 语法规则 + `PUT N*:` 节点选择;点错(锚在 `def` 会让装饰器变成孤儿)会悄悄落错;无语法检查 |
231
231
  | 多编辑批量中途失败 | `edit` 多条目——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
232
232
 
@@ -264,39 +264,47 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
264
264
 
265
265
  ## 工具
266
266
 
267
- | 工具 | 作用 |
268
- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
269
- | `read` | 以 `HASH│内容` 形式返回文件。参数:`offset`(1 起始)、`limit`。分页输出以 `[Showing lines N-M of T. Use offset=… to continue.]` 结尾。超过 200KB 的行显示为标记并附 `sed` 提示——哈希锚点需要完整行。 |
270
- | `edit` | 对象根负载 `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`;`path` 可为 `null` 以通过锚点推断。单个条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
271
- | `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
267
+ | 工具 | 作用 |
268
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
269
+ | `read` | 以 `HASH│内容` 形式返回文件。参数:`offset`(1 起始)、`limit`。分页输出以 `[Showing lines N-M of T. Use offset=… to continue.]` 结尾。超过 200KB 的行显示为标记并附 `sed` 提示——哈希锚点需要完整行。 |
270
+ | `edit` | `{file, edits:[[from,to,text]]}`(也接受命名对象;`path`/`file_path` 别名会被折叠),`""` 删除,原子 ≤32,先校验后写入。单条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
271
+ | `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
272
272
 
273
273
  内置 `write` 仍用于整文件替换。执行前,插件只会在候选行以同一会话、规范路径及行位置所提供的精确 `HASH│` 锚点开头时拒绝;文件保持不变,并提示仅用文件正文重试。插件不会泛化地剥离类似哈希的文本。
274
274
 
275
275
  ### 错误码
276
276
 
277
- | 代码 | 含义 |
278
- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
279
- | `[E_ACCESS]` | 文件存在但工具不可读/不可写。 |
280
- | `[E_AMBIGUOUS_ANCHOR]` | 一个哈希匹配当前多行;调用 `read` 获取新锚点。 |
281
- | `[E_BAD_OP]` | 范围结束先于范围开始(首尾颠倒时会自动纠正)。 |
282
- | `[E_BAD_REF]` | `remove_from`/`remove_to` 不是裸 3 字符哈希。 |
283
- | `[E_BAD_SHAPE]` | 请求/字段形态错误(未知字段、缺少 path、非字符串文本等)。 |
284
- | `[E_BARE_HASH_PREFIX]` | `HASH│` 前缀被粘贴进 `replacement_text`(自动纠正)。 |
285
- | `[E_BATCH_ABORT]` | 批次内某项失败;整个批次被拒绝,未写入任何内容。 |
286
- | `[E_FILE_TOO_LARGE]` | 文件超过 hashline 行数上限;请改用 `write` 或其他方式。 |
287
- | `[E_INVALID_PATCH]` | diff 预览标记被粘贴进 `replacement_text`(自动纠正)。 |
288
- | `[E_NOOP_LOOP]` | 完全相同的编辑反复不产生任何变化;再次提交会被拒绝。 |
289
- | `[E_NOT_FOUND]` | 文件不存在。 |
290
- | `[E_NOT_OBSERVED]` | 该文件在本会话中尚未被观察(先读后写策略);请先调用 `read`。 |
291
- | `[E_NOT_TEXT]` | 路径是目录、二进制或非 UTF-8 文件;hashline 只能编辑文本。 |
292
- | `[E_WRITE_HASH_ECHO]` | 内置 `write` 候选内容复制了同一会话、路径及行位置所提供的 `HASH│` 预览锚点。写入在执行前被拒绝;移除整条复制的锚点链后重试。 |
293
- | `[E_RANGE_STALE]` | 某行自被读取以来在磁盘上发生变化;范围以全新锚点回显。 |
294
- | `[E_RANGE_UNSERVED]` | 范围内包含从未提供给模型的行。 |
295
- | `[E_RANGE_UNVERIFIED]` | 边界锚点无法对照已提供状态验证。 |
296
- | `[E_STALE_ANCHOR]` | 锚点不再能解析;调用 `read` 获取新锚点。 |
297
- | `[E_UNDO_STALE]` | 无法撤销:编辑之后文件被修改(或删除)。 |
298
- | `[E_UNDO_UNAVAILABLE]` | 撤销历史无法持久化;编辑未被应用。 |
299
- | `[E_WOULD_EMPTY]` | 编辑会把非空文件清空;请用 `write` 清空。 |
277
+ | 代码 | 含义 | 处理方式 |
278
+ | ------------------------- | --------------------------------------------------- | ------------------------------------------------ |
279
+ | `[E_BAD_PAYLOAD]` | 请求形态错误(未知字段、缺少 `file`、元组位置错误) | 修正形态后重发 |
280
+ | `[E_MALFORMED_ANCHOR]` | 锚点不是裸 3 字符锚点(粘贴的块或伪锚点) | 传裸锚点后重试 |
281
+ | `[E_UNKNOWN_ANCHOR]` | 该锚点从未为本文件提供过 | `read` 获取新锚点 |
282
+ | `[E_FOREIGN_ANCHOR]` | 该锚点属于其他文件或会话 | 使用本文件提供的锚点 |
283
+ | `[E_STALE_ANCHOR]` | 锚点已无法解析(哈希/已退役/规范化失配) | `read` 获取新锚点 |
284
+ | `[E_AMBIGUOUS_MATCH]` | `str_replace` 的 `old_str` 命中多处 | 扩大 `old_str` 上下文 |
285
+ | `[E_NO_MATCH]` | `str_replace` 的 `old_str` 不存在 | 重新 `view` 后重试 |
286
+ | `[E_EMPTY_RANGE]` | 编辑会清空非空文件 | 改用 `write` |
287
+ | `[E_STALE_RANGE]` | 已提供的范围在磁盘上发生变化 | 使用回显的新行 |
288
+ | `[E_UNSERVED_RANGE]` | 范围内包含从未提供的行 | `read` 该范围 |
289
+ | `[E_UNVERIFIED_RANGE]` | 边界锚点无法对照已提供状态校验 | `read` 后重试 |
290
+ | `[E_SUSPICIOUS_TEXT]` | 替换文本含复制的 `HASH│` 或 diff 预览标记 | 移除后重发 |
291
+ | `[E_BLIND_REPLACE]` | `write` / `str_replace_editor` 在观察文件前执行 | 先 `read` / `view` |
292
+ | `[E_TARGET_LOST]` | 目标在操作中途消失或身份改变 | `read` 后重新定位 |
293
+ | `[E_BATCH_ABORT]` | 批次中某项失败,未写入任何内容 | 修正该项后重发批次 |
294
+ | `[E_NOOP_LOOP]` | 同一空操作编辑被反复提交 | 修改编辑内容 |
295
+ | `[E_ACCESS]` | 路径不可读或不可写 | 修正权限 |
296
+ | `[E_NOT_FOUND]` | 文件不存在 | 检查父目录 |
297
+ | `[E_FILE_EXISTS]` | `create` 目标已存在 | 换一个路径 |
298
+ | `[E_UNSUPPORTED_FILE]` | 目录、二进制或非文本文件 | 选择文本文件 |
299
+ | `[E_ENCODING_UNWRITABLE]` | 记录的编码无法由 UTF-8 文本写入复现 | 设 `normalizeToUtf8: true` 迁移,或在插件外编辑 |
300
+ | `[E_UNSUPPORTED]` | `str_replace_editor undo_edit` 未实现 | 改用 `undo_last_edit` |
301
+ | `[E_BAD_COMMAND]` | 未知的 `str_replace_editor` 命令 | 使用 `view`、`str_replace`、`insert` 或 `create` |
302
+ | `[E_LARGE_FILE]` | 超过行数或锚点空间上限 | 改用 `write` 或拆分文件 |
303
+ | `[E_UNDO_STALE]` | 编辑之后文件被修改 | 无法撤销;重新读取 |
304
+ | `[E_UNDO_UNAVAILABLE]` | 撤销历史无法持久化 | 重试编辑 |
305
+ | `[E_UNDO_NOT_RECORDED]` | 回滚已落盘但存储未能记录 | 重新读取;下次撤销会清掉旧历史 |
306
+ | `[E_STORE_NEWER_VERSION]` | 存储由更新版本的插件写入 | 升级插件,或改用其他存储目录 |
307
+ | `[E_UNKNOWN]` | 未预期的内部错误 | 上报;消息原文保留 |
300
308
 
301
309
  ## 如何替换内置工具
302
310
 
package/lib/contract.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * declared once here; every tool validates through these asserts, and the
5
5
  * E_BAD_PAYLOAD vocabulary is shared instead of re-implemented per tool.
6
6
  *
7
- * Contract mirrors upstream ADR-0015: {file: string|null, edits: [{anchor_from, anchor_to, replace_with},...]} named-object payload
7
+ * Contract mirrors upstream ADR-0015: {file: string, edits: [{anchor_from, anchor_to, replace_with},...]} named-object payload
8
8
  * (plus legacy tuple items and legacy key spellings folded pre-validation), single-file, atomic. batch_edit is removed.
9
9
  * @module dsh-better-edit/contract
10
10
  */
@@ -70,8 +70,8 @@ export function editRequestFrom(input) {
70
70
  return undefined;
71
71
  }
72
72
  const { file, file_path, path, edits, mode } = rec;
73
- // file preferred; legacy path/file_path fold (sanitized). null stays null:
74
- // the undocumented anchor-inference seam (resolveNullPath) still resolves it.
73
+ // file preferred; legacy path/file_path fold (sanitized). #117: a null or
74
+ // absent file is an admission error — the anchor-inference seam is retired.
75
75
  let effectiveFile;
76
76
  if (file !== undefined)
77
77
  effectiveFile = file;
@@ -81,19 +81,11 @@ export function editRequestFrom(input) {
81
81
  effectiveFile = file_path;
82
82
  else
83
83
  return undefined;
84
- let effectivePath;
85
- if (typeof effectiveFile === "string") {
86
- const sanitized = sanitizePath(effectiveFile);
87
- if (sanitized === null)
88
- return undefined;
89
- effectivePath = sanitized;
90
- }
91
- else if (effectiveFile === null) {
92
- effectivePath = null;
93
- }
94
- else {
84
+ if (typeof effectiveFile !== "string")
85
+ return undefined;
86
+ const effectivePath = sanitizePath(effectiveFile);
87
+ if (effectivePath === null)
95
88
  return undefined;
96
- }
97
89
  if (!Array.isArray(edits) || edits.length === 0)
98
90
  return undefined;
99
91
  const items = [];
@@ -218,7 +210,47 @@ export function prepareEditArguments(args) {
218
210
  });
219
211
  }
220
212
  // ---- assertions ---------------------------------------------------------------
213
+ /** The spellings a caller may name the target with, in payload precedence order. */
214
+ const FILE_SPELLINGS = ["file", "path", "file_path"];
215
+ /** The exact refusal ADR-0031 quotes; one sentence, one owner. */
216
+ const FILE_REQUIRED_MESSAGE = "Edit request file must be a non-empty string; name the file to edit.";
217
+ /**
218
+ * #117: is this raw record an unnamed target rather than a malformed payload?
219
+ *
220
+ * `normalizeRequest` stamps its marker only when `editRequestFrom` succeeds, and
221
+ * the fold rejects a null/absent file — so without this predicate the specific
222
+ * refusal is unreachable and the caller only sees the generic hint. A spelling
223
+ * that is present but wrongly typed is malformed, not unnamed, and stays generic.
224
+ */
225
+ function namesNoFile(request) {
226
+ let seesUnnamed = false;
227
+ for (const key of FILE_SPELLINGS) {
228
+ if (!(key in request))
229
+ continue;
230
+ const value = request[key];
231
+ if (typeof value === "string") {
232
+ if (sanitizePath(value) !== null)
233
+ return false; // a usable name wins
234
+ seesUnnamed = true;
235
+ continue;
236
+ }
237
+ if (value === null || value === undefined) {
238
+ seesUnnamed = true;
239
+ continue;
240
+ }
241
+ return false; // present but wrongly typed: malformed payload
242
+ }
243
+ // No spelling at all is still unnamed when the record carries an edit payload;
244
+ // a record naming nothing and carrying nothing keeps the generic hint.
245
+ return seesUnnamed || Array.isArray(request.edits);
246
+ }
221
247
  export function assertEditRequest(request) {
248
+ // #117: the specific refusal must be reachable before the marker guard — a raw
249
+ // record whose file is null/absent/empty never normalizes, so the generic hint
250
+ // would otherwise be the only message the caller sees.
251
+ if (isRec(request) && namesNoFile(request)) {
252
+ throw new DomainError("E_BAD_PAYLOAD", { message: FILE_REQUIRED_MESSAGE });
253
+ }
222
254
  if (!isNormalizedEdit(request)) {
223
255
  throw new DomainError("E_BAD_PAYLOAD", {
224
256
  message: 'Edit request must be exactly { file, edits: [{ anchor_from, anchor_to, replace_with }, ...], mode?: "general" | "literal" }. ' +
@@ -227,9 +259,9 @@ export function assertEditRequest(request) {
227
259
  }
228
260
  rejectUnknownFields(request, EDIT_KS, "Edit request");
229
261
  const req = request;
230
- if (req.file !== null && (typeof req.file !== "string" || req.file.length === 0)) {
262
+ if (typeof req.file !== "string" || req.file.length === 0) {
231
263
  throw new DomainError("E_BAD_PAYLOAD", {
232
- message: "Edit request file must be a non-empty string or null.",
264
+ message: FILE_REQUIRED_MESSAGE,
233
265
  });
234
266
  }
235
267
  if (req.mode !== undefined && req.mode !== "general" && req.mode !== "literal") {
@@ -295,13 +327,12 @@ export const anchorToSchema = {
295
327
  };
296
328
  export const pathSchema = {
297
329
  type: "string",
298
- description: "File path; null infers it from anchors",
330
+ description: "File path",
299
331
  };
300
332
  export const editPathSchema = {
301
- anyOf: [
302
- { type: "string", minLength: 1, description: "File path; null infers it from anchors" },
303
- { type: "null", description: "null infers path from anchors" },
304
- ],
333
+ type: "string",
334
+ minLength: 1,
335
+ description: "Text file to edit (a file, never a directory)",
305
336
  };
306
337
  export const editTupleSchema = {
307
338
  type: "array",
@@ -303,6 +303,12 @@ export const ERROR_REGISTRY = {
303
303
  // WHY remedy: detection classified the target — kind (directory, binary or image) proves it is not an editable text file.
304
304
  remedy: "Choose a text file and retry.",
305
305
  },
306
+ E_ENCODING_UNWRITABLE: {
307
+ audience: "MODEL",
308
+ format: ({ path, encoding }) => `Cannot write ${path}: it was read as ${encoding}, and this filesystem exposes only a text write that always encodes UTF-8. Writing now would transcode the file silently, and its anchors would no longer describe the bytes on disk. Nothing was written. Set normalizeToUtf8: true (DSH_BETTER_EDIT_NORMALIZE_TO_UTF8=true) to migrate the file to UTF-8 explicitly, then retry.`,
309
+ // WHY remedy: the recorded encoding proves the text seam cannot reproduce it, and normalizeToUtf8 is the one setting that makes the write legal.
310
+ remedy: "Set normalizeToUtf8: true to migrate the file to UTF-8 explicitly, then retry.",
311
+ },
306
312
  E_ACCESS: {
307
313
  audience: "MODEL",
308
314
  format: accessFormat,
@@ -432,7 +438,7 @@ export const WARNING_REGISTRY = {
432
438
  format: () => "served-echo check bypassed by literal declaration.",
433
439
  },
434
440
  W_NOOP: {
435
- audience: "USER",
441
+ audience: "MODEL",
436
442
  format: noopWarnFormat,
437
443
  },
438
444
  };
@@ -14,9 +14,32 @@
14
14
  *
15
15
  * @module dsh-better-edit/file-encoding-state
16
16
  */
17
- import { detectBom, isValidUtf8, decodeBytes, normalizeEncoding, top3Candidates, chardetTop3Candidates, } from "./encoding.js";
17
+ import { detectBom, isValidUtf8, decodeBytes, encodeText, normalizeEncoding, top3Candidates, chardetTop3Candidates, } from "./encoding.js";
18
18
  import { detectEnding, restoreEndings, toLF } from "./edit-diff.js";
19
19
  import { DomainError, formatError } from "./domain-errors.js";
20
+ /**
21
+ * The decode hint a mutating re-read must pass to the byte seam: the encoding
22
+ * recorded by the preceding `read({ encoding })` — but only while the memo still
23
+ * matches the on-disk version, and only for encodings the plain read path cannot
24
+ * reproduce.
25
+ *
26
+ * `utf8` / `utf8bom` need no hint: BOM sniff + strict UTF-8 (and the bridge's
27
+ * stripped-BOM restore) already decode them to the text the anchors were served
28
+ * for, so asking for a byte reread would only cost an RPC. Everything else
29
+ * (utf16le, windows-1251, GBK, …) is invisible to the plain path — without the
30
+ * hint the mutation re-read decodes lossily or fails, which is the stale-anchor /
31
+ * unsupported-file symptom this hint removes (issue #112).
32
+ *
33
+ * A drifted memo is dropped first, so a changed file is re-detected instead of
34
+ * having the old encoding laundered onto its new bytes.
35
+ */
36
+ export function encodingHintAtVersion(targetKey, currentVersion) {
37
+ invalidateIfStale(targetKey, currentVersion);
38
+ const encoding = encodingMemo.get(targetKey)?.encoding;
39
+ if (encoding === undefined || encoding === "utf8" || encoding === "utf8bom")
40
+ return undefined;
41
+ return encoding;
42
+ }
20
43
  const encodingMemo = new Map();
21
44
  const autoGuessFooterMemo = new Map();
22
45
  export function getEncodingState(targetKey) {
@@ -280,43 +303,97 @@ export function recordFooter(targetKey, footer) {
280
303
  * Prefer `prepareForSave` / `stripBOM` over re-implementing this check. */
281
304
  export const UTF8_BOM = "\uFEFF";
282
305
  /**
283
- * Decide what bytes (as text, since provider expects string) to write and
284
- * what new state to record. BOM and lineEnding are restored here when a
285
- * previous state exists; otherwise defaults are UTF-8 without BOM and LF.
286
- * For legacy encodings with normalizeToUtf8:false, we preserve the memo
287
- * (provider will write UTF-8 string, next read re-detects via version bump).
306
+ * True when the text's UTF-8 byte image is byte-identical to its byte image
307
+ * under `encoding` — an ASCII-only file in a single-byte charset, where the
308
+ * text-only write seam reproduces the original bytes exactly. Checking bytes
309
+ * (not the encoding name) is what keeps that file editable.
310
+ *
311
+ * This is a property of the TEXT only. A recorded `hasBOM` is a property of the
312
+ * FILE and is checked separately at the call site: the legacy BOM bytes cannot be
313
+ * reproduced by a UTF-8 string write (a UTF-8 BOM is a different byte image).
314
+ */
315
+ export function isByteFaithfulAsUtf8(text, encoding) {
316
+ if (encoding === "utf8" || encoding === "utf8bom")
317
+ return true;
318
+ const encoded = encodeText(text, encoding);
319
+ if (encoded === undefined)
320
+ return false;
321
+ const utf8 = new TextEncoder().encode(text);
322
+ if (encoded.length !== utf8.length)
323
+ return false;
324
+ for (let i = 0; i < utf8.length; i += 1)
325
+ if (encoded[i] !== utf8[i])
326
+ return false;
327
+ return true;
328
+ }
329
+ /**
330
+ * Decide what bytes (as text, since the write seam takes a string) to write and
331
+ * what new state to record. BOM and lineEnding are restored here when a state
332
+ * exists; otherwise defaults are UTF-8 without BOM and LF.
333
+ *
334
+ * ROUND-TRIP VERDICT: the bridge's only write is `writeText(target, content:
335
+ * string, …)`, which every backend encodes as UTF-8. So the save side can
336
+ * restore BOM + line ending for the UTF-8 family, and can write a legacy file
337
+ * only when its UTF-8 byte image is identical (ASCII-only). Anything else
338
+ * throws `E_ENCODING_UNWRITABLE` BEFORE the write, because writing UTF-8 would
339
+ * silently transcode the file and leave the anchors describing other bytes.
340
+ * `normalizeToUtf8: true` is the explicit migration: write UTF-8 and record
341
+ * `utf8` so the next read agrees with the bytes.
288
342
  */
289
343
  export function prepareForSave(content, existingState, opts = {}) {
344
+ const displayPath = opts.displayPath ?? "(unknown path)";
345
+ const normalize = opts.normalizeToUtf8 === true;
290
346
  if (opts.encodingHint) {
291
347
  const norm = normalizeEncoding(opts.encodingHint);
292
348
  if (!norm)
293
349
  throw new DomainError("E_BAD_PAYLOAD", { message: `Unknown encoding: ${opts.encodingHint}` });
350
+ // A non-UTF-8 hint names an encoding the UTF-8 text write cannot reproduce
351
+ // except byte-faithfully; a recorded BOM adds bytes it cannot reproduce at all.
352
+ const hintFaithful = (norm === "utf8" || norm === "utf8bom" || isByteFaithfulAsUtf8(content, norm)) &&
353
+ !(existingState?.hasBOM === true && norm !== "utf8bom");
354
+ if (!hintFaithful)
355
+ throw new DomainError("E_ENCODING_UNWRITABLE", { path: displayPath, encoding: norm });
294
356
  const hasBOM = norm === "utf8bom";
295
357
  const lineEnding = existingState?.lineEnding ?? detectEnding(content);
296
- // Caller will write `content` as UTF-8 string; record new state for next read.
358
+ // Caller writes `content` as a UTF-8 string; record what the next read detects.
297
359
  return {
298
360
  textToWrite: content,
299
361
  newState: { encoding: norm, hasBOM, lineEnding, version: undefined },
300
362
  };
301
363
  }
302
- if (existingState &&
303
- !opts.normalizeToUtf8 &&
304
- existingState.encoding !== "utf8" &&
305
- existingState.encoding !== "utf8bom") {
306
- // Legacy file, normalize false — preserve memo on wire (no transcode),
307
- // provider writes UTF-8 string, version bump will invalidate on next read.
364
+ if (!existingState) {
365
+ // New file, no memo: UTF-8, caller's own line endings.
308
366
  return { textToWrite: content };
309
367
  }
310
- // Default: restore recorded BOM + lineEnding via the shared seam so
311
- // governed writers (e.g. the str_replace_editor shadow) don't re-implement
312
- // the round-trip locally and diverge on future utf16le/lineEnding evolution.
313
- // Only add, never strip: a missing memo means UTF-8 without BOM + LF.
314
- let textToWrite = content;
315
- if (existingState?.lineEnding) {
316
- textToWrite = restoreEndings(toLF(textToWrite), existingState.lineEnding);
368
+ const recorded = existingState.encoding;
369
+ const lineEnding = existingState.lineEnding ?? detectEnding(content);
370
+ if (recorded !== "utf8" && recorded !== "utf8bom") {
371
+ const body = restoreEndings(toLF(content), lineEnding);
372
+ // A recorded BOM on a non-UTF-8 encoding means bytes the text write cannot
373
+ // reproduce (e.g. read({ encoding: "windows-1251" }) on a UTF-8-BOM file, or
374
+ // utf16le's FF FE), so even an ASCII body is not byte-faithful there.
375
+ const faithful = !existingState.hasBOM && isByteFaithfulAsUtf8(body, recorded);
376
+ if (!normalize && !faithful) {
377
+ throw new DomainError("E_ENCODING_UNWRITABLE", { path: displayPath, encoding: recorded });
378
+ }
379
+ // Migration (normalizeToUtf8) or a byte-faithful legacy image: both land UTF-8
380
+ // bytes, so the memo must describe UTF-8 — never a stale utf16le/legacy name.
381
+ return {
382
+ textToWrite: body,
383
+ newState: { encoding: "utf8", hasBOM: false, lineEnding, version: undefined },
384
+ };
317
385
  }
318
- if (existingState?.hasBOM && !textToWrite.startsWith(UTF8_BOM)) {
386
+ // UTF-8 family: restore the recorded BOM + lineEnding via the shared seam so
387
+ // governed writers (e.g. the str_replace_editor shadow) don't re-implement the
388
+ // round-trip locally and diverge on future lineEnding evolution.
389
+ // Only add, never strip: a missing BOM means UTF-8 without BOM.
390
+ let textToWrite = restoreEndings(toLF(content), lineEnding);
391
+ if (existingState.hasBOM && !textToWrite.startsWith(UTF8_BOM)) {
319
392
  textToWrite = `${UTF8_BOM}${textToWrite}`;
320
393
  }
321
- return { textToWrite };
394
+ const hasBOM = textToWrite.startsWith(UTF8_BOM);
395
+ return {
396
+ textToWrite,
397
+ newState: { encoding: hasBOM ? "utf8bom" : "utf8", hasBOM, lineEnding, version: undefined },
398
+ };
322
399
  }