dsh-better-edit 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,38 @@ 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] - 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
+ - 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`.
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.4.0-rc.1] - 2026-08-24
26
+
27
+ ### Added
28
+
29
+ - 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.
30
+ - Readable `runtime/<name>-<hash8>/` with `.wsPath` sidecar for collision proof.
31
+
32
+ ### Changed
33
+
34
+ - 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`.
35
+ - 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`.
36
+
37
+ ### Fixed
38
+
39
+ - `.gitignore` pollution warning for `workspace` mode and idempotent `autoGitignore` opt-in (yaml+env `true|false`).
40
+
9
41
  ## [0.3.2] - 2026-08-23
10
42
 
11
43
  ### Fixed
@@ -32,7 +64,6 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
32
64
 
33
65
  - Docs: `CLAUDE.md` upstream sync section — last absorbed checkpoint `7b91958` (dense `servedRows`), procedure, checkpoint history, `upstream` remote.
34
66
 
35
-
36
67
  ## [0.3.0] - 2026-08-20
37
68
 
38
69
  ### Changed
@@ -44,7 +75,6 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
44
75
  - Notices & prompts hygiene: Zed-style terse drift/noop/rejection notices (codes unchanged), lean guidelines (dedupe tool descriptions), tool schema descriptions trimmed to one-liners.
45
76
  - 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).
46
77
 
47
-
48
78
  ## [0.2.2] - 2026-08-19
49
79
 
50
80
  ### 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}`);
@@ -92,15 +93,15 @@ export function ctxFsIO(fs, ctx) {
92
93
  return {
93
94
  async resolve(path, cwd, signal) {
94
95
  const target = await fs.resolve(path, {
95
- ...(cwd !== undefined ? { cwd } : {}),
96
- ...(signal !== undefined ? { signal } : {}),
96
+ ...(cwd === undefined ? {} : { cwd }),
97
+ ...(signal === undefined ? {} : { signal }),
97
98
  });
98
99
  return fs.processPath(target);
99
100
  },
100
101
  async readText(absolutePath, signal) {
101
102
  try {
102
103
  const target = await fs.resolve(absolutePath, {
103
- ...(signal !== undefined ? { signal } : {}),
104
+ ...(signal === undefined ? {} : { signal }),
104
105
  });
105
106
  const text = await fs.readText(target, signal);
106
107
  return await restoreStrippedUtf8Bom(fs, target, text, signal);
@@ -112,7 +113,7 @@ export function ctxFsIO(fs, ctx) {
112
113
  async writeText(absolutePath, content, signal, exec, sandboxPolicy) {
113
114
  try {
114
115
  const target = await fs.resolve(absolutePath, {
115
- ...(signal !== undefined ? { signal } : {}),
116
+ ...(signal === undefined ? {} : { signal }),
116
117
  });
117
118
  // Single-slot decision: the observation policy produces
118
119
  // createIfAbsent / replaceIfVersion; the bare default is
@@ -137,7 +138,7 @@ export function ctxFsIO(fs, ctx) {
137
138
  async emitObserved(absolutePath, exec, signal) {
138
139
  try {
139
140
  const target = await fs.resolve(absolutePath, {
140
- ...(signal !== undefined ? { signal } : {}),
141
+ ...(signal === undefined ? {} : { signal }),
141
142
  });
142
143
  const info = await fs.stat(target, signal);
143
144
  if (info !== undefined) {
@@ -152,7 +153,7 @@ export function ctxFsIO(fs, ctx) {
152
153
  async statVersion(absolutePath, signal) {
153
154
  try {
154
155
  const target = await fs.resolve(absolutePath, {
155
- ...(signal !== undefined ? { signal } : {}),
156
+ ...(signal === undefined ? {} : { signal }),
156
157
  });
157
158
  const info = await fs.stat(target, signal);
158
159
  return info?.version ?? undefined;
package/lib/hash-store.js CHANGED
@@ -13,15 +13,16 @@
13
13
  * reaches into another family's rows.
14
14
  * @module dsh-better-edit/hash-store
15
15
  */
16
- import { existsSync } from "node:fs";
17
- import { readFile, rename, mkdir, stat } from "node:fs/promises";
16
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
17
+ import { readFile, readdir, rename, rm, mkdir, stat } from "node:fs/promises";
18
18
  import { dirname, join } from "node:path";
19
19
  import { DatabaseSync } from "node:sqlite";
20
- import { hashStorePath } from "./paths.js";
20
+ import { hashStorePath } from "./store-tenancy.js";
21
+ import { onStoreOpen, setStoresGetter } from "./store-lifecycle.js";
21
22
  import { workspaceCwd } from "./workspace.js";
22
23
  import { errCode, splitLines } from "./utils.js";
23
- import { initHasher, contentChecksum, HASH_RE, CANON_VERSION } from "./hashline/hash-assign.js";
24
- import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
24
+ import { initHasher, contentChecksum, HASH_RE, CANON_VERSION, } from "./hashline/hash-assign.js";
25
+ import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS, } from "./constants.js";
25
26
  export function isValidHashList(value) {
26
27
  if (!Array.isArray(value))
27
28
  return false;
@@ -54,6 +55,10 @@ export function isValidServedList(value) {
54
55
  function cacheKey(checksum) {
55
56
  return `${CANON_VERSION}:${checksum}`;
56
57
  }
58
+ /** Load the store as served persistence — internal, for SessionView only. */
59
+ export function loadServedStore(cwd) {
60
+ return loadHashStore(cwd);
61
+ }
57
62
  // ---- db plumbing (private) --------------------------------------------------
58
63
  export function isCorruptionError(error) {
59
64
  if (error && typeof error === "object") {
@@ -103,6 +108,7 @@ function openDbWithBusyRetry(storePath) {
103
108
  /** One open store per store path (per workspace); parallel sessions share per-workspace dbs. */
104
109
  const stores = new Map();
105
110
  const openings = new Map();
111
+ setStoresGetter(() => stores, () => openings);
106
112
  let exitHandlerRegistered = false;
107
113
  function openDb(storePath) {
108
114
  const db = new DatabaseSync(storePath, {
@@ -115,8 +121,8 @@ function openDb(storePath) {
115
121
  try {
116
122
  db.close();
117
123
  }
118
- catch {
119
- // best-effort close when the store build fails
124
+ catch (error) {
125
+ console.warn(error); // best-effort close when the store build fails
120
126
  }
121
127
  throw error;
122
128
  }
@@ -147,8 +153,7 @@ function buildStore(db) {
147
153
  const versionRow = db
148
154
  .prepare("SELECT value FROM meta WHERE key = 'version'")
149
155
  .get();
150
- const versionChanged = versionRow !== undefined &&
151
- versionRow.value !== String(HASH_STORE_VERSION);
156
+ const versionChanged = versionRow !== undefined && versionRow.value !== String(HASH_STORE_VERSION);
152
157
  if (versionChanged) {
153
158
  db.exec("DELETE FROM snapshots");
154
159
  db.exec("DELETE FROM undo");
@@ -166,8 +171,10 @@ function buildStore(db) {
166
171
  "updated_at INTEGER NOT NULL, " +
167
172
  "PRIMARY KEY (session_id, path)" +
168
173
  ")");
169
- db.prepare("INSERT INTO meta (key, value) VALUES ('version', ?) " +
170
- "ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(HASH_STORE_VERSION));
174
+ db
175
+ .prepare("INSERT INTO meta (key, value) VALUES ('version', ?) " +
176
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value")
177
+ .run(String(HASH_STORE_VERSION));
171
178
  const getStmt = db.prepare("SELECT hashes FROM snapshots WHERE path = ? AND checksum = ? AND line_count = ?");
172
179
  const allStmt = db.prepare("SELECT path FROM snapshots UNION SELECT path FROM undo UNION SELECT path FROM served");
173
180
  const allHashesStmt = db.prepare("SELECT path, hashes FROM snapshots");
@@ -178,6 +185,7 @@ function buildStore(db) {
178
185
  "ON CONFLICT(path) DO UPDATE SET content = excluded.content, bom = excluded.bom, ending = excluded.ending, hashes = excluded.hashes, result_content = excluded.result_content, updated_at = excluded.updated_at");
179
186
  const undoGetStmt = db.prepare("SELECT content, bom, ending, hashes, result_content FROM undo WHERE path = ?");
180
187
  const undoDelStmt = db.prepare("DELETE FROM undo WHERE path = ?");
188
+ const undoPruneOlderThanStmt = db.prepare("DELETE FROM undo WHERE updated_at < ?");
181
189
  const servedGetStmt = db.prepare("SELECT hashes, reported FROM served WHERE session_id = ? AND path = ?");
182
190
  const servedUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, updated_at) VALUES (?, ?, ?, ?) " +
183
191
  "ON CONFLICT(session_id, path) DO UPDATE SET hashes = excluded.hashes, updated_at = excluded.updated_at");
@@ -213,6 +221,11 @@ function buildStore(db) {
213
221
  undoDelStmt.run(...params);
214
222
  });
215
223
  },
224
+ undoPruneOlderThan: (...params) => {
225
+ withBusyRetry(() => {
226
+ undoPruneOlderThanStmt.run(...params);
227
+ });
228
+ },
216
229
  servedGet: (...params) => servedGetStmt.get(...params),
217
230
  servedUpsert: (...params) => {
218
231
  withBusyRetry(() => {
@@ -270,7 +283,7 @@ function makeDomainStore(stmts) {
270
283
  stmts.deleteOne(path);
271
284
  return undefined;
272
285
  }
273
- catch {
286
+ catch (error) {
274
287
  if (deleteCorrupt)
275
288
  stmts.deleteOne(path);
276
289
  return undefined;
@@ -299,8 +312,8 @@ function makeDomainStore(stmts) {
299
312
  if (hashes.every((h) => parsed.includes(h)))
300
313
  matches.push(row.path);
301
314
  }
302
- catch {
303
- // unparseable row → skip it
315
+ catch (error) {
316
+ console.warn(error); // unparseable row → skip it
304
317
  }
305
318
  }
306
319
  return matches;
@@ -323,7 +336,7 @@ function makeDomainStore(stmts) {
323
336
  resultContent: row.result_content,
324
337
  };
325
338
  }
326
- catch {
339
+ catch (error) {
327
340
  stmts.undoDelete(path);
328
341
  return undefined;
329
342
  }
@@ -345,7 +358,7 @@ function makeDomainStore(stmts) {
345
358
  stmts.servedDelete(sessionKey, path);
346
359
  return [];
347
360
  }
348
- catch {
361
+ catch (error) {
349
362
  stmts.servedDelete(sessionKey, path);
350
363
  return [];
351
364
  }
@@ -363,7 +376,7 @@ function makeDomainStore(stmts) {
363
376
  return new Set();
364
377
  return new Set(parsed.filter((h) => typeof h === "string" && HASH_RE.test(h)));
365
378
  }
366
- catch {
379
+ catch (error) {
367
380
  return new Set();
368
381
  }
369
382
  },
@@ -388,6 +401,9 @@ function makeDomainStore(stmts) {
388
401
  pruneServedOlderThan(ts) {
389
402
  stmts.servedPruneOlderThan(ts);
390
403
  },
404
+ pruneUndoOlderThan(ts) {
405
+ stmts.undoPruneOlderThan(ts);
406
+ },
391
407
  async pruneMissing() {
392
408
  const rows = stmts.allPaths();
393
409
  const missing = await statMissing(rows);
@@ -431,8 +447,8 @@ function shutdownDb(db) {
431
447
  try {
432
448
  db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
433
449
  }
434
- catch {
435
- // best-effort checkpoint before close
450
+ catch (error) {
451
+ console.warn(`dsh-better-edit: wal_checkpoint failed on shutdown: ${error instanceof Error ? error.message : String(error)}`); // best-effort checkpoint before close
436
452
  }
437
453
  db.close();
438
454
  }
@@ -484,21 +500,9 @@ async function openStore(storePath) {
484
500
  if (!existed) {
485
501
  await migrateLegacy(db, storePath);
486
502
  }
487
- withBusyRetry(() => {
488
- stmts.servedPruneOlderThan(Date.now() - SERVED_TTL_MS);
489
- });
490
503
  const store = makeDomainStore(stmts);
491
504
  stores.set(storePath, { path: storePath, db, stmts, store });
492
- if (!exitHandlerRegistered) {
493
- exitHandlerRegistered = true;
494
- process.once("exit", () => shutdownHashStore());
495
- for (const sig of ["SIGINT", "SIGTERM"]) {
496
- process.once(sig, () => {
497
- shutdownHashStore();
498
- process.kill(process.pid, sig);
499
- });
500
- }
501
- }
505
+ await onStoreOpen(storePath, stmts, store);
502
506
  return store;
503
507
  }
504
508
  /** Resolve the store path for this call: explicit cwd, the active workspace, or the shared-home fallback. */
@@ -557,8 +561,8 @@ export function withStore(fn) {
557
561
  try {
558
562
  store.db.exec("ROLLBACK");
559
563
  }
560
- catch {
561
- // best-effort rollback; the original error propagates
564
+ catch (error) {
565
+ console.warn(error); // best-effort rollback; the original error propagates
562
566
  }
563
567
  throw e;
564
568
  }