dsh-better-edit 0.3.1 → 0.4.0-rc.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
@@ -6,6 +6,28 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.4.0-rc.1] - 2026-08-24
10
+
11
+ ### Added
12
+
13
+ - Configurable store tenancy with central default (`$DSH_HOME/plugins/dsh-better-edit/runtime/<name>-<hash8>/`), `workspace` legacy opt-in, and custom `/abs` root — yaml at `$DSH_HOME/plugins/dsh-better-edit/config.yaml` (`storeDir` — where the store lives, `autoGitignore` — workspace .gitignore handling, `undo_ttl_s` — undo TTL in seconds (-1 = forever), `storeMaxAgeS` — central janitor max idle age in seconds (default 30 days), `storeMaxTotalBytes` — central janitor max total bytes) + god envs `DSH_BETTER_EDIT_STORE_DIR`/`DSH_BETTER_EDIT_AUTO_GITIGNORE` (`env > yaml > central`) with malformed fallback to central and warnings. DB files are disposable caches — safe to delete, rebuilt on next `read` ([#24](https://github.com/Rianico/dsh-better-edit/issues/24)). Thanks to [@MrWeiCodes](https://github.com/MrWeiCodes) for the proposal and design discussion.
14
+ - Migration probe copies legacy `<workspace>/.dsh_better_edit/` once on first central open; readable `runtime/<name>-<hash8>/` with `.wsPath` sidecar for collision proof.
15
+
16
+ ### Changed
17
+
18
+ - Default store location moved from workspace-co-located to central `runtime/` to eliminate git pollution and zip privacy leakage — `workspace` now requires explicit `storeDir: workspace`. Existing workspace stores are migrated automatically on first access.
19
+ - Store lifecycle now plugin-owned for central/custom (throttled janitor on `apply` + `agent/session-start` >24h, `mtime>storeMaxAgeS` (default 30 days / 2592000 s, unified to seconds with `undo_ttl_s`) then LRU to `count<100 && sum<500MB`, never deleting live `hash(workspaceCwd)`), `wal_checkpoint(TRUNCATE)` on close/janitor, `undo` TTL `undo_ttl_s` (default 7d, `-1` = forever, seconds), `pruneMissing` batch 64 — workspace mode remains user-owned with row TTL only. DB files are disposable caches — safe to delete, rebuilt on next `read`.
20
+
21
+ ### Fixed
22
+
23
+ - `.gitignore` pollution warning for `workspace` mode and idempotent `autoGitignore` opt-in (yaml+env `true|false`).
24
+
25
+ ## [0.3.2] - 2026-08-23
26
+
27
+ ### Fixed
28
+
29
+ - Preserve a stripped UTF-8 BOM across `ctx.fs`-backed `edit` and `undo_last_edit` writes while retaining the file's original line endings (#23).
30
+
9
31
  ## [0.3.1] - 2026-08-21
10
32
 
11
33
  ### Changed
@@ -26,7 +48,6 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
26
48
 
27
49
  - Docs: `CLAUDE.md` upstream sync section — last absorbed checkpoint `7b91958` (dense `servedRows`), procedure, checkpoint history, `upstream` remote.
28
50
 
29
-
30
51
  ## [0.3.0] - 2026-08-20
31
52
 
32
53
  ### Changed
@@ -38,7 +59,6 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
38
59
  - Notices & prompts hygiene: Zed-style terse drift/noop/rejection notices (codes unchanged), lean guidelines (dedupe tool descriptions), tool schema descriptions trimmed to one-liners.
39
60
  - README brooks-lint reorg + CONTEXT glossary merge: hook, shining points, Why Hashline before Tools, benchmark section referencing `pi-better-edit/benchmarks/results/` (same hashline algorithm).
40
61
 
41
-
42
62
  ## [0.2.2] - 2026-08-19
43
63
 
44
64
  ### Added
package/README.md CHANGED
@@ -129,6 +129,70 @@ One fails, none write (`[E_BATCH_ABORT]`).
129
129
  > [!TIP]
130
130
  > **Want proof before you install?** The upstream [23/23 tool battery](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/README.md) runs with no LLM — stale edits are rejected before they corrupt a file, on every run. Same hashline algorithm, same verification.
131
131
 
132
+ ### Configuration
133
+
134
+ Tenancy and prompt guidance are both declared once, read at `agent/session-start`, and need no code changes.
135
+
136
+ #### Store tenancy — central by default
137
+
138
+ The store lives at `$DSH_HOME/plugins/dsh-better-edit/runtime/<name>-<hash8>/` by default (`central`).
139
+
140
+ > [!NOTE]
141
+ > DB files are **disposable caches** — they are rebuilt automatically on the next `read` (hashes are re-derived from file content). Feel free to `rm -rf` any `runtime/<name>-<hash8>/` or `hash-store.sqlite*` to reclaim disk; no user data is lost (only anchor history and undo snapshots).
142
+
143
+ To opt into legacy co-location or a custom root:
144
+
145
+ ```yaml
146
+ # $DSH_HOME/plugins/dsh-better-edit/config.yaml
147
+ storeDir: central # where the store lives: "central" (default, in $DSH_HOME/.../runtime/<name>-<hash8>/) | "workspace" (legacy <ws>/.dsh_better_edit/) | "/abs/path" (custom root)
148
+ autoGitignore: false # workspace only: when .git exists but .gitignore lacks .dsh_better_edit/, true = auto-append ".dsh_better_edit/", false = warn once
149
+ undo_ttl_s: 604800 # undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
150
+ storeMaxAgeS: 2592000 # central janitor: max idle age in seconds before a runtime/<name>-<hash8>/ dir is evicted (default 2592000 = 30 days)
151
+ storeMaxTotalBytes: 524288000 # central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
152
+ ```
153
+
154
+ > [!TIP]
155
+ > If the file does not exist, a default `config.yaml` with commented defaults is generated on first boot (never overwrites an existing file).
156
+
157
+ Env overrides yaml (`env > yaml > central`), malformed falls back to `central` with a warning:
158
+
159
+ ```sh
160
+ DSH_BETTER_EDIT_STORE_DIR=central|workspace|/abs
161
+ DSH_BETTER_EDIT_AUTO_GITIGNORE=true|false # case-insensitive
162
+ ```
163
+
164
+ `runtime/<name>-<hash8>/` is `ls`-readable with a `.wsPath` sidecar. See `docs/specs/issue-24-store-tenancy.md` for lifecycle (janitor `mtime>storeMaxAgeS` then LRU, WAL checkpoint, `undo` TTL).
165
+
166
+ #### Guidance per preset
167
+
168
+ The `tool:read` / `tool:edit` / `tool:undo_last_edit` prompt sections are plain-markdown files per agent preset, overridable without touching the plugin:
169
+
170
+ ```
171
+ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
172
+ ```
173
+
174
+ (default home `~/.dsh`, so `~/.dsh/plugins/dsh-better-edit/`). The section table:
175
+
176
+ | File | Section | Default order |
177
+ | --- | --- | --- |
178
+ | `read.md` | `tool:read` | 130 |
179
+ | `edit.md` | `tool:edit` | 131 |
180
+ | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
181
+
182
+ On first boot the plugin seeds the three shipped presets — `standard/`, `code/`, `minimal/`, `cordis/` — each with the compiled guidance as editable files (plus `order` front-matter). See [Configuration details](#configuring-guidance-per-preset) for reset/restore. Full spec: `docs/specs/issue-24-store-tenancy.md` and guidance docs.
183
+
184
+ ##### Reset / restore defaults
185
+
186
+ Emptying or deleting an override file restores that section's compiled default guidance and order: the default renders at session-start, and the file re-seeds at next boot.
187
+
188
+ - **Reset = delete the file, or empty it AND remove the front-matter fence.** A whitespace-only file with no fence means "I want the default" — the compiled default renders, and the file re-seeds at next boot for any preset dir, shipped or custom.
189
+ - **Blank on purpose = keep a valid fence.** Any well-formed `---` fence — even a keyless `---\n---\n`, even an empty body — is a deliberate-intent signal: the file is explicit content and is never reset or re-seeded.
190
+ - **Broken fence = fast fail.** A `---` fence that does not parse (missing closing `---`, non-integer `order`, unknown key) is rejected: the malformed text is never injected into the context, the compiled default renders, a warning names the file and the reason, and the file is left untouched on disk for repair.
191
+ - **Shipped vs custom.** Shipped preset files (`standard`, `code`, `minimal`, `cordis`) re-seed at boot; a deleted custom-preset override stays absent — absence is no override. Deleting a whole `<preset>/` directory re-seeds all three section files at boot (shipped presets).
192
+ - **Reset restores the current bundle defaults** — a plugin upgrade yields new defaults.
193
+
194
+ Re-seeding happens at boot, never mid-session.
195
+
132
196
  ## Why Hashline
133
197
 
134
198
  **Correctness, not just brevity.** Every resolved edit range is verified against the
@@ -306,44 +370,7 @@ Reproduce via upstream: `npm run eval` in `pi-better-edit` (this plugin shares t
306
370
  Full method, per-scenario tables, and limitations: upstream [benchmarks/README.md](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/README.md)
307
371
  and [benchmarks/results/](https://github.com/Rianico/pi-better-edit/tree/main/benchmarks/results).
308
372
 
309
- ## Configuring Guidance per Preset
310
-
311
- The `tool:read` / `tool:edit` / `tool:undo_last_edit` guidance sections are
312
- plain-markdown files, overridable per agent preset. Override files live in the plugin's shared
313
- home — never the workspace store:
314
-
315
- ```
316
- $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
317
- ```
318
-
319
- (default home `~/.dsh`, so `~/.dsh/plugins/dsh-better-edit/`). The section table:
320
-
321
- | File | Section | Default order |
322
- | --- | --- | --- |
323
- | `read.md` | `tool:read` | 130 |
324
- | `edit.md` | `tool:edit` | 131 |
325
- | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
326
-
327
- On first boot the plugin seeds the three shipped presets — `standard/`, `code/`,
328
- `minimal/`, `cordis/` — each with the compiled guidance as editable files (plus
329
- `order` front-matter), so every preset's guidance starts editable rather than
330
- blank. A `README.md` at the plugin-home root documents the scheme. Files are
331
- seeded once and never rewritten, so your edits survive — a reset is the one
332
- exception (see *Reset / restore defaults* below).
333
-
334
- ### Reset / restore defaults
335
-
336
- Emptying or deleting an override file restores that section's compiled default
337
- guidance and order: the default renders at session-start, and the file re-seeds
338
- at next boot.
339
-
340
- - **Reset = delete the file, or empty it AND remove the front-matter fence.** A whitespace-only file with no fence means "I want the default" — the compiled default renders, and the file re-seeds at next boot for any preset dir, shipped or custom.
341
- - **Blank on purpose = keep a valid fence.** Any well-formed `---` fence — even a keyless `---\n---\n`, even an empty body — is a deliberate-intent signal: the file is explicit content and is never reset or re-seeded.
342
- - **Broken fence = fast fail.** A `---` fence that does not parse (missing closing `---`, non-integer `order`, unknown key) is rejected: the malformed text is never injected into the context, the compiled default renders, a warning names the file and the reason, and the file is left untouched on disk for repair.
343
- - **Shipped vs custom.** Shipped preset files (`standard`, `code`, `minimal`, `cordis`) re-seed at boot; a deleted custom-preset override stays absent — absence is no override. Deleting a whole `<preset>/` directory re-seeds all three section files at boot (shipped presets).
344
- - **Reset restores the current bundle defaults** — a plugin upgrade yields new defaults.
345
-
346
- Re-seeding happens at boot, never mid-session.
373
+ > See [Configuration](#configuration) under [Quick Start](#quick-start) for guidance overrides and store tenancy.
347
374
 
348
375
  ## How Anchors Work
349
376
 
@@ -392,20 +419,9 @@ registration cannot replace them. This plugin:
392
419
 
393
420
  ## Store
394
421
 
395
- Hash snapshots, served-state rows, and undo history live in one SQLite store **co-located with the
396
- workspace being edited** — one store per session cwd:
397
-
398
- ```
399
- <workspace>/.dsh_better_edit/hash-store.sqlite
400
- ```
401
-
402
- Parallel sessions in different workspaces keep separate stores (the session cwd is carried through
403
- each tool call), so one project's anchors and undo history never leak into another's. Outside a tool
404
- call (tests, previews) the store falls back to the shared DeepSeek Harness home
405
- (`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`).
422
+ Hash snapshots, served-state rows, and undo history live in one SQLite store — **central by default** (`$DSH_HOME/plugins/dsh-better-edit/runtime/<name>-<hash8>/hash-store.sqlite`, `ls`-readable with `.wsPath` sidecar). Legacy co-located `<workspace>/.dsh_better_edit/` is still supported via `storeDir: workspace` in `config.yaml` and is copied once on first central open. Parallel sessions in different workspaces keep separate stores (the session cwd is carried through each tool call), so one project's anchors and undo history never leak into another's. Outside a tool call (tests, previews) the store falls back to the shared DeepSeek Harness home (`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`).
406
423
 
407
- A 7-day TTL prunes served rows; missing-file snapshots are pruned at startup. Corrupt stores are
408
- quarantined and rebuilt automatically.
424
+ A 7-day TTL prunes served rows; `undo_ttl_s` (default 7d, `-1` forever) prunes undo clones; missing-file snapshots are pruned on throttled `openStore`; corrupt stores are quarantined and rebuilt automatically. The central janitor (`apply` + `agent/session-start` throttled >24h) evicts `mtime>storeMaxAgeS` (default 2592000 s = 30 days) then LRU to `count<100 && sum<500MB`, never deleting live `hash(workspaceCwd)`, with `wal_checkpoint(TRUNCATE)` on close. DB files are disposable caches — safe to delete, rebuilt on next `read`.
409
425
 
410
426
  ## Project Structure
411
427
 
package/README.zh.md CHANGED
@@ -54,6 +54,7 @@ Hashline 用两个哈希代替旧文本——**编辑 token 减少 31%**(多
54
54
 
55
55
  > [!TIP]
56
56
  > **亮点——诚实且可衡量:**
57
+ >
57
58
  > - **自愈而非静默。** 外部编辑永不被覆盖——过期范围被拒绝并以全新 `HASH│content` 重发重试;孤儿 served 条目无需全量重读即可自愈(ADR-0008)。Fail-closed,而非自动合并。
58
59
  > - **格式化容忍。** ASCII 空白不敏感锚点在 `prettier`/`black`/`eslint --fix` 之间存活(`formatOnSave`、监听、CI)。仅限 linter 场景——字符串内的空白不区分(ADR-0005)。
59
60
  > - **链式与批量,无重读仪式。** 未受影响行的锚点保持有效;diff/回显/拒绝行即视为已提供。`edit` 最多 32 个同文件编辑原子执行(`[E_BATCH_ABORT]`),相比 `str_replace` 信封约 -40%。
@@ -109,16 +110,51 @@ kQm│}
109
110
  kQm │ }
110
111
  ```
111
112
 
112
- ## 按 preset 配置指引
113
+ > 详见[快速开始](#快速开始)中[配置](#配置)一节的指引覆盖与存储租约。
114
+
115
+ ### 配置
116
+
117
+ 租约与提示词指引都只需声明一次,在 `agent/session-start` 时读取,无需改代码。
118
+
119
+ #### 存储租约 — 默认 central
120
+
121
+ 默认无仓库污染。存储位于 `$DSH_HOME/plugins/dsh-better-edit/runtime/<name>-<hash8>/`(`central`)。
122
+
123
+ > [!NOTE]
124
+ > DB 文件是**可丢弃的缓存**——下次调用 `read` 时会自动重建(哈希值由文件内容重新推导)。可随时 `rm -rf` 任意 `runtime/<name>-<hash8>/` 或 `hash-store.sqlite*` 以回收磁盘;不会丢失用户数据(仅丢失锚点历史和撤销快照)。
125
+
126
+ 如需回退到旧的同址或自定义根:
127
+
128
+ ```yaml
129
+ # $DSH_HOME/plugins/dsh-better-edit/config.yaml
130
+ storeDir: central # 存储位置:"central"(默认,位于 $DSH_HOME/.../runtime/<name>-<hash8>/)| "workspace"(旧版 <ws>/.dsh_better_edit/)| "/abs/path"(自定义根目录)
131
+ autoGitignore: false # 仅 workspace:当 .git 存在但 .gitignore 缺少 .dsh_better_edit/ 时,true = 自动追加 ".dsh_better_edit/",false = 仅告警一次
132
+ undo_ttl_s: 604800 # 撤销历史 TTL(秒);-1 = 永久保留(默认 604800 = 7 天)
133
+ storeMaxAgeS: 2592000 # central 清理:runtime/<name>-<hash8>/ 目录最大闲置时长(秒),超时后被清理(默认 2592000 = 30 天)
134
+ storeMaxTotalBytes: 524288000 # central 清理:runtime/ 下总字节数上限,超限后按 LRU 清理(默认 524288000 = 500 MB)
135
+ ```
136
+
137
+ > [!TIP]
138
+ > 若文件不存在,首次启动时会自动生成带注释的默认 `config.yaml`(永不覆盖已有文件)。
139
+
140
+ Env 覆盖 yaml(`env > yaml > central`),非法回退到 `central` 并告警:
141
+
142
+ ```sh
143
+ DSH_BETTER_EDIT_STORE_DIR=central|workspace|/abs
144
+ DSH_BETTER_EDIT_AUTO_GITIGNORE=true|false # 大小写不敏感
145
+ ```
146
+
147
+ 旧的 `<workspace>/.dsh_better_edit/` 在首次以 central 打开时一次性拷贝;`runtime/<name>-<hash8>/` 可通过 `ls` 查看,带 `.wsPath` 旁路文件。生命周期详见 `docs/specs/issue-24-store-tenancy.md`(janitor `mtime>storeMaxAgeS` 后 LRU、WAL checkpoint、`undo` TTL)。
113
148
 
114
- `tool:read` / `tool:edit` / `tool:undo_last_edit` 三个提示词片段的指引是
115
- 纯 Markdown 文件,可以按 agent preset 覆盖。覆盖文件位于插件的共享主目录——绝不放在工作区存储中:
149
+ #### 按 preset 的指引
150
+
151
+ `tool:read` / `tool:edit` / `tool:undo_last_edit` 的提示词片段是按 agent preset 覆盖的纯 Markdown 文件,无需改插件:
116
152
 
117
153
  ```
118
154
  $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
119
155
  ```
120
156
 
121
- (默认主目录为 `~/.dsh`,即 `~/.dsh/plugins/dsh-better-edit/`)。片段对照表:
157
+ (默认主目录 `~/.dsh`,即 `~/.dsh/plugins/dsh-better-edit/`)。片段对照表:
122
158
 
123
159
  | 文件 | 提示词片段 | 默认 order |
124
160
  | --- | --- | --- |
@@ -126,28 +162,9 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
126
162
  | `edit.md` | `tool:edit` | 131 |
127
163
  | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
128
164
 
129
- 首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的
130
- 可编辑指引文件(含 `order` front-matter),让每个 preset 的指引一开始就可编辑,而不是空白。插件主目录
131
- 根的 `README.md` 说明整套机制。文件只在首次写入时生成、之后绝不被覆盖,因此你的修改会保留——唯一的例外是重置(见下文 *重置 / 恢复默认*)。preset 目录
132
- 里可以只放你想覆盖的片段文件,其余自动回退到编译内置默认值。
133
-
134
- 文件默认为纯文本;除非以 `order` front-matter 栅栏开头,它会改变该片段在组装后的系统提示中的位置:
135
-
136
- ```md
137
- ---
138
- order: 150
139
- ---
140
-
141
- <片段文本>
142
- ```
143
-
144
- 每个片段的解析顺序为:读取 `<preset>/<section>.md`,否则回退到编译内置默认值。文件只在 agent 的
145
- session-start 时读取一次,因此修改只影响新会话——绝不影响进行中的会话。没有种子目录的 preset(例如
146
- 用户自建的)会回退到编译内置默认值,除非你把某个种子目录复制成它的名字。没有 `agentPresets` 服务
147
- (即没有 preset 名册)的部署继续使用编译内置默认值,完全不会触碰这些文件;
148
- preset 从来不是必需的。
165
+ 首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的可编辑指引文件(含 `order` front-matter)。详见[配置详情](#按-preset-配置指引)的重置/恢复。完整规范:`docs/specs/issue-24-store-tenancy.md` 与指引文档。
149
166
 
150
- ### 重置 / 恢复默认
167
+ ##### 重置 / 恢复默认
151
168
 
152
169
  **想让指引“回到默认”?删掉覆盖文件,或把它清空(同时删掉开头的 `---` 栅栏)即可。**
153
170
 
@@ -285,15 +302,9 @@ dsh 的工具注册表按作用域解析:agent 看到的是 `agent → preset
285
302
 
286
303
  ## 存储
287
304
 
288
- 哈希快照、已提供状态行与撤销历史存放在一个 SQLite 库中,**与被编辑的工作区放在一起**——每个会话 cwd 一个库:
289
-
290
- ```
291
- <workspace>/.dsh_better_edit/hash-store.sqlite
292
- ```
293
-
294
- 不同工作区中的并行会话各自持有独立的库(会话 cwd 会随每次工具调用传递),因此一个项目的锚点与撤销历史不会泄漏到另一个项目。在工具调用之外(测试、预览)会回退到共享的 DeepSeek Harness 主目录(`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`)。
305
+ 哈希快照、已提供状态行与撤销历史存放在一个 SQLite 库中——**默认 central**(`$DSH_HOME/plugins/dsh-better-edit/runtime/<name>-<hash8>/hash-store.sqlite`,可通过 `ls` 查看,带 `.wsPath` 旁路文件)。旧的同址 `<workspace>/.dsh_better_edit/` 仍可通过 `config.yaml` 中 `storeDir: workspace` 启用,并在首次以 central 打开时一次性拷贝。不同工作区的并行会话各自持有独立的库(会话 cwd 会随每次工具调用传递),因此一个项目的锚点与撤销历史不会泄漏到另一个项目。在工具调用之外(测试、预览)会回退到共享的 DeepSeek Harness 主目录(`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`)。
295
306
 
296
- 7 天 TTL 会清理已提供的行;启动时清理缺失文件的快照。损坏的库会被隔离并自动重建。迁移到按工作区布局**不会**迁移共享主目录中的早期撤销历史——把 0.1.2 之前的撤销记录视为已丢失。
307
+ 7 天 TTL 清理已提供的行;`undo_ttl_s`(默认 7 天,`-1` 永久)清理撤销副本;缺失文件的快照在受控的 `openStore` 中清理;损坏的库会被隔离并自动重建。 central 的 janitor(`apply` + `agent/session-start` 受控节流 >24h)会先清理 `mtime>storeMaxAgeS`(默认 2592000 秒 = 30 天),再按 LRU 至 `count<100 && sum<500MB`,永不删除存活的 `hash(workspaceCwd)`,并在关闭时执行 `wal_checkpoint(TRUNCATE)`。DB 文件为可丢弃缓存——可安全删除,下次 `read` 时重建。
297
308
 
298
309
  ## 项目结构
299
310
 
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Canonical path resolution — single seam for symlink-aware canonicalization.
3
+ * Pure traversal owns the visited-set + ELOOP + ENOENT (lexical tail) invariant.
4
+ * Two adapters justify the seam: sync (hash8, sanitizedBasename, central tenancy)
5
+ * and async (resolveTarget). Byte-identical to the previous duplicated impl.
6
+ * @module dsh-better-edit/canonical-path
7
+ */
8
+ import { dirname, join, parse, sep } from "node:path";
9
+ import { resolve as resolvePath } from "node:path";
10
+ import { lstat as lstatAsync, readlink as readlinkAsync } from "node:fs/promises";
11
+ import { lstatSync, readlinkSync } from "node:fs";
12
+ import { errCode } from "./utils.js";
13
+ function splitAfterRoot(absolutePath) {
14
+ const { root } = parse(absolutePath);
15
+ return {
16
+ root,
17
+ parts: absolutePath.slice(root.length).split(sep).filter((p) => p.length > 0),
18
+ };
19
+ }
20
+ function eLoopError(ws) {
21
+ const e = new Error(`Too many symbolic links while resolving ${ws}`);
22
+ e.code = "ELOOP";
23
+ return e;
24
+ }
25
+ /** Sync adapter — lstatSync + readlinkSync. */
26
+ export function canonicalSync(inputPath) {
27
+ const absolutePath = resolvePath(inputPath);
28
+ const { root, parts } = splitAfterRoot(absolutePath);
29
+ const visited = new Set();
30
+ let current = root;
31
+ let remaining = parts.slice();
32
+ while (remaining.length > 0) {
33
+ const [next, ...tail] = remaining;
34
+ const candidate = join(current, next);
35
+ try {
36
+ const st = lstatSync(candidate);
37
+ if (!st.isSymbolicLink()) {
38
+ current = candidate;
39
+ remaining = tail;
40
+ continue;
41
+ }
42
+ if (visited.has(candidate))
43
+ throw eLoopError(inputPath);
44
+ visited.add(candidate);
45
+ const linkTarget = resolvePath(dirname(candidate), readlinkSync(candidate));
46
+ const targetParts = splitAfterRoot(linkTarget);
47
+ current = targetParts.root;
48
+ remaining = [...targetParts.parts, ...tail];
49
+ }
50
+ catch (error) {
51
+ if (errCode(error) === "ENOENT")
52
+ return join(candidate, ...tail);
53
+ throw error;
54
+ }
55
+ }
56
+ return current;
57
+ }
58
+ /** Async adapter — lstat + readlink. Thin async shell over the same traversal. */
59
+ export async function canonicalAsync(inputPath) {
60
+ const absolutePath = resolvePath(inputPath);
61
+ const { root, parts } = splitAfterRoot(absolutePath);
62
+ const visited = new Set();
63
+ async function resParts(currentPath, remainingParts) {
64
+ if (remainingParts.length === 0)
65
+ return currentPath;
66
+ const [nextPart, ...tail] = remainingParts;
67
+ const candidatePath = join(currentPath, nextPart);
68
+ try {
69
+ const candidateStats = await lstatAsync(candidatePath);
70
+ if (!candidateStats.isSymbolicLink())
71
+ return resParts(candidatePath, tail);
72
+ if (visited.has(candidatePath))
73
+ throw eLoopError(inputPath);
74
+ visited.add(candidatePath);
75
+ const linkTargetPath = resolvePath(dirname(candidatePath), await readlinkAsync(candidatePath));
76
+ const targetParts = splitAfterRoot(linkTargetPath);
77
+ return resParts(targetParts.root, [...targetParts.parts, ...tail]);
78
+ }
79
+ catch (error) {
80
+ if (errCode(error) === "ENOENT")
81
+ return join(candidatePath, ...tail);
82
+ throw error;
83
+ }
84
+ }
85
+ return resParts(root, parts);
86
+ }
package/lib/fs-bridge.js CHANGED
@@ -28,6 +28,7 @@ import { resolveTarget, toCwd } from "./paths.js";
28
28
  export function mapFsError(error, displayPath) {
29
29
  if (error instanceof Error &&
30
30
  typeof error.code === "string") {
31
+ // SAFETY: `error` narrowed to Error with string `code` above — typed extraction for FS code switch
31
32
  const code = error.code;
32
33
  if (code === "FS_NOT_FOUND") {
33
34
  throw new Error(`[E_NOT_FOUND] File not found: ${displayPath}`);
@@ -50,22 +51,60 @@ export function mapFsError(error, displayPath) {
50
51
  }
51
52
  throw error;
52
53
  }
54
+ const UTF8_BOM = "\uFEFF";
55
+ const UTF8_BOM_BYTES = [0xef, 0xbb, 0xbf];
56
+ const UTF8_BOM_LEN = UTF8_BOM_BYTES.length;
57
+ /**
58
+ * Restore a UTF-8 BOM consumed by a backend's {@link TextDecoder}. The raw
59
+ * byte seam reads whole files rather than prefixes, so first use stat size to
60
+ * narrow the expensive probe to the only possible BOM case: exactly three
61
+ * storage bytes are missing from the decoded UTF-8 representation.
62
+ *
63
+ * Compensation for upstream BOM stripping: `dsh-fs-local` decodes with
64
+ * `TextDecoder("utf-8",{fatal:true})` (`ignoreBOM:false` by default) and
65
+ * swallows leading `EF BB BF`.
66
+ * https://github.com/deepseek-ai/deepseek-harness/discussions/1026
67
+ * https://github.com/Rianico/dsh-better-edit/issues/23
68
+ */
69
+ async function restoreStrippedUtf8Bom(fs, target, text, signal) {
70
+ if (text.startsWith(UTF8_BOM))
71
+ return text;
72
+ const info = await fs.stat(target, signal);
73
+ if (info?.size === undefined ||
74
+ info.size !== Buffer.byteLength(text, "utf-8") + UTF8_BOM_LEN) {
75
+ return text;
76
+ }
77
+ const bytes = await fs.readBytes(target, signal, info.size);
78
+ const encodedText = Buffer.from(text, "utf-8");
79
+ if (bytes.length !== encodedText.length + UTF8_BOM_LEN ||
80
+ bytes[0] !== UTF8_BOM_BYTES[0] ||
81
+ bytes[1] !== UTF8_BOM_BYTES[1] ||
82
+ bytes[2] !== UTF8_BOM_BYTES[2]) {
83
+ return text;
84
+ }
85
+ for (let i = 0; i < encodedText.length; i += 1) {
86
+ if (bytes[i + UTF8_BOM_LEN] !== encodedText[i])
87
+ return text;
88
+ }
89
+ return `${UTF8_BOM}${text}`;
90
+ }
53
91
  /** FileIO over the deployment's `ctx.fs` service. */
54
92
  export function ctxFsIO(fs, ctx) {
55
93
  return {
56
94
  async resolve(path, cwd, signal) {
57
95
  const target = await fs.resolve(path, {
58
- ...(cwd !== undefined ? { cwd } : {}),
59
- ...(signal !== undefined ? { signal } : {}),
96
+ ...(cwd === undefined ? {} : { cwd }),
97
+ ...(signal === undefined ? {} : { signal }),
60
98
  });
61
99
  return fs.processPath(target);
62
100
  },
63
101
  async readText(absolutePath, signal) {
64
102
  try {
65
103
  const target = await fs.resolve(absolutePath, {
66
- ...(signal !== undefined ? { signal } : {}),
104
+ ...(signal === undefined ? {} : { signal }),
67
105
  });
68
- return await fs.readText(target, signal);
106
+ const text = await fs.readText(target, signal);
107
+ return await restoreStrippedUtf8Bom(fs, target, text, signal);
69
108
  }
70
109
  catch (error) {
71
110
  return mapFsError(error, absolutePath);
@@ -74,7 +113,7 @@ export function ctxFsIO(fs, ctx) {
74
113
  async writeText(absolutePath, content, signal, exec, sandboxPolicy) {
75
114
  try {
76
115
  const target = await fs.resolve(absolutePath, {
77
- ...(signal !== undefined ? { signal } : {}),
116
+ ...(signal === undefined ? {} : { signal }),
78
117
  });
79
118
  // Single-slot decision: the observation policy produces
80
119
  // createIfAbsent / replaceIfVersion; the bare default is
@@ -99,7 +138,7 @@ export function ctxFsIO(fs, ctx) {
99
138
  async emitObserved(absolutePath, exec, signal) {
100
139
  try {
101
140
  const target = await fs.resolve(absolutePath, {
102
- ...(signal !== undefined ? { signal } : {}),
141
+ ...(signal === undefined ? {} : { signal }),
103
142
  });
104
143
  const info = await fs.stat(target, signal);
105
144
  if (info !== undefined) {
@@ -114,7 +153,7 @@ export function ctxFsIO(fs, ctx) {
114
153
  async statVersion(absolutePath, signal) {
115
154
  try {
116
155
  const target = await fs.resolve(absolutePath, {
117
- ...(signal !== undefined ? { signal } : {}),
156
+ ...(signal === undefined ? {} : { signal }),
118
157
  });
119
158
  const info = await fs.stat(target, signal);
120
159
  return info?.version ?? undefined;