dsh-retrace 0.4.150 → 0.4.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ it cannot dirty the log, and new markers create **no token-meter pairing debt**
35
35
 
36
36
  > Versions: [VERSIONS.md](./VERSIONS.md)
37
37
 
38
- > **0.4.150 is the current release** — install/pin `0.4.150` (the **GitHub Release is out; the npm package is still pending** — the latest npm version is `0.4.139`; see [VERSIONS.md](./VERSIONS.md)). The `dsh-retrace@0.4.150` examples below apply to this release.
38
+ > **0.4.152 is the current release** — install/pin `0.4.152` (the **GitHub Release is out; the npm package is still pending** — the latest npm version is `0.4.139`; see [VERSIONS.md](./VERSIONS.md)). The `dsh-retrace@0.4.152` examples below apply to this release.
39
39
 
40
40
  ## ⚡ One-minute install
41
41
 
@@ -153,7 +153,7 @@ The same result with plain file edits and `pnpm` — exactly the steps
153
153
  ```json
154
154
  {
155
155
  "dependencies": {
156
- "dsh-retrace": "^0.4.150"
156
+ "dsh-retrace": "^0.4.152"
157
157
  },
158
158
  "dsh": {
159
159
  "profile": {
@@ -221,7 +221,8 @@ The dynamic host registers the same operations behind the package-private
221
221
 
222
222
  - DeepSeek Harness providing the peer packages listed in `package.json`
223
223
  (`@deepseek-ai/dsh-session`, `@deepseek-ai/dsh-client-*`, `cordis`, `react` — the
224
- current build targets the `0.1.7-rc.2` generation).
224
+ build baseline is the `0.1.7-rc.2` generation; the declared range also accepts the
225
+ `0.2.x` line: `>=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0`).
225
226
  - `dsh-log-contract >= 0.3.18` (installed automatically as a dependency).
226
227
  - The plugin declares the host capabilities it needs via `inject`
227
228
  (`sessions`, `agents`, `webServer`, `fs`, `subprocess`, `sandboxPolicy`, `jobs`).
@@ -257,7 +258,7 @@ Before you exit or reload, know what is still running:
257
258
  > handler, or a pre-quit prompt hook). If the app cannot quit, turning off "Exit
258
259
  > confirmation (close guard)" recovers immediately (no restart).
259
260
 
260
- ### External binding id (optional)
261
+ ## 🧬 External binding id (optional)
261
262
 
262
263
  - The plugin **does not generate or assign conversation identifiers**, keeps **no mapping table**, and **never renames or prefixes conversation titles**.
263
264
  - A **read-only** per-session binding id surface remains for integrations: host ops **`sessionBadge`** (one session) and **`badgeMap`** (all sessions). Reading it has no write path.
@@ -353,7 +354,7 @@ Historical details and exact error strings live in [CHANGELOG.md](./CHANGELOG.md
353
354
  ### Upgrading
354
355
 
355
356
  ```bash
356
- dsh plugin --profile desktop add dsh-retrace@0.4.150
357
+ dsh plugin --profile desktop add dsh-retrace@0.4.152
357
358
  # then restart DSH — plugins are not hot-reloaded
358
359
  ```
359
360
 
@@ -377,7 +378,7 @@ whole tree down, so recover first and diagnose second:
377
378
 
378
379
  ### Pinning
379
380
 
380
- Pin an exact plugin version (`dsh-retrace@0.4.150`) and let `dsh-log-contract` resolve to
381
+ Pin an exact plugin version (`dsh-retrace@0.4.152`) and let `dsh-log-contract` resolve to
381
382
  `>=0.3.18`. Do not rely on `^0.4` across a host upgrade: compatibility here is decided by
382
383
  the **host surface**, not by semver alone.
383
384
 
package/README.zh.md CHANGED
@@ -30,7 +30,7 @@
30
30
 
31
31
  > 版本索引:[VERSIONS.md](./VERSIONS.md)
32
32
 
33
- > **0.4.150 为当前版本**——安装/固定请用 `0.4.150`(**GitHub Release 已发,npm 待发**;npm 最新可安装版本仍为 `0.4.139`,见 [VERSIONS.md](./VERSIONS.md));下文的 `dsh-retrace@0.4.150` 示例适用于该版本。
33
+ > **0.4.152 为当前版本**——安装/固定请用 `0.4.152`(**GitHub Release 已发,npm 待发**;npm 最新可安装版本仍为 `0.4.139`,见 [VERSIONS.md](./VERSIONS.md));下文的 `dsh-retrace@0.4.152` 示例适用于该版本。
34
34
 
35
35
  ## ⚡ 一分钟安装
36
36
 
@@ -137,7 +137,7 @@ dsh plugin --profile <name> add dsh-retrace
137
137
  ```json
138
138
  {
139
139
  "dependencies": {
140
- "dsh-retrace": "^0.4.150"
140
+ "dsh-retrace": "^0.4.152"
141
141
  },
142
142
  "dsh": {
143
143
  "profile": {
@@ -199,7 +199,8 @@ Client 半区会依据包内 `dsh.client` 元数据被自动打包进 Web 客户
199
199
 
200
200
  - DeepSeek Harness 需提供 `package.json` 里声明的 peer 包
201
201
  (`@deepseek-ai/dsh-session`、`@deepseek-ai/dsh-client-*`、`cordis`、`react` ——
202
- 当前构建面向 `0.1.7-rc.2` 这一代内核)。
202
+ 构建基线是 `0.1.7-rc.2` 这一代内核,声明范围同时接受 `0.2.x` 线:
203
+ `>=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0`)。
203
204
  - `dsh-log-contract >= 0.3.18`(作为依赖自动安装)。
204
205
  - 插件通过 `inject` 声明所需宿主能力
205
206
  (`sessions`、`agents`、`webServer`、`fs`、`subprocess`、`sandboxPolicy`、`jobs`)。
@@ -314,7 +315,7 @@ Client 半区会依据包内 `dsh.client` 元数据被自动打包进 Web 客户
314
315
  ### 升级
315
316
 
316
317
  ```bash
317
- dsh plugin --profile desktop add dsh-retrace@0.4.150
318
+ dsh plugin --profile desktop add dsh-retrace@0.4.152
318
319
  # 然后重启 DSH —— 插件不会热重载
319
320
  ```
320
321
 
@@ -333,7 +334,7 @@ dsh plugin --profile desktop add dsh-retrace@0.4.150
333
334
 
334
335
  ### 版本固定建议
335
336
 
336
- 请固定到确切版本(`dsh-retrace@0.4.150`),并让 `dsh-log-contract` 解析到 `>=0.3.18`。
337
+ 请固定到确切版本(`dsh-retrace@0.4.152`),并让 `dsh-log-contract` 解析到 `>=0.3.18`。
337
338
  **不要在跨宿主升级时依赖 `^0.4` 这种范围**:这里的兼容性由**宿主的面**决定,光看 semver 不够。
338
339
 
339
340
  ---
@@ -43,16 +43,26 @@ export const CHECKPOINT_TICKET_TTL_MS = 120_000
43
43
  export const CHECKPOINT_MAX_FILE_BYTES = 1024 * 1024
44
44
  /** A pending checkpoint older than this is a crash leftover, not an operation. */
45
45
  export const CHECKPOINT_PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000
46
+ /** 后台剪枝周期(启动之外的低频维护;只删超龄 pending,不动有效记录)。 */
47
+ export const CHECKPOINT_PENDING_PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000
46
48
 
47
49
  const EXCLUDED_SEGMENTS = new Set(['.git', 'node_modules'])
48
50
  const HEX64 = /^[0-9a-f]{64}$/
49
51
 
50
52
  const sha256Of = (bytes) => createHash('sha256').update(bytes).digest('hex')
51
53
 
54
+ /**
55
+ * 字节 → 文本;二进制/非 UTF-8 ⇒ **稳定错误码 `binary-unsupported`**。
56
+ *
57
+ * 为什么要单独一个码:宿主 fs seam(0.1.7-rc.2 与 0.2.2-rc.2 两线)只有文本变更原语
58
+ * (`writeText`/`patchText`,见 docs/COMPAT.md 的“二进制文件”一节),二进制前像
59
+ * **没有官方回写 seam**。这里失败要让调用方/用户看到「二进制,无法回写」,而不是
60
+ * 一个含糊的 `unsupported`,更不能把乱码写回去。
61
+ */
52
62
  const textOf = (bytes) => {
53
63
  const buffer = Buffer.from(bytes)
54
64
  const text = buffer.toString('utf8')
55
- if (text.includes('\0') || !Buffer.from(text).equals(buffer)) throw editorError('unsupported', 'binary-or-encoding')
65
+ if (text.includes('\0') || !Buffer.from(text).equals(buffer)) throw editorError('binary-unsupported', 'binary-or-encoding')
56
66
  return text
57
67
  }
58
68
 
@@ -564,9 +574,23 @@ export function createCheckpointRestore({
564
574
  artifacts.push({ path: row.path, status: 'deleted' })
565
575
  continue
566
576
  }
567
- const text = textOf(await preimages.objectStore.read(row.sha256))
577
+ const bytes = await preimages.objectStore.read(row.sha256)
568
578
  const policy = ctx.sandboxPolicy?.resolve?.({ session })
569
- await ctx.fs.writeText(row.target, text, row.version === null ? { kind: 'createIfAbsent' } : replaceIfVersion(row.version), undefined, policy)
579
+ const expected = row.version === null ? { kind: 'createIfAbsent' } : replaceIfVersion(row.version)
580
+ let text = null
581
+ try {
582
+ text = textOf(bytes)
583
+ } catch (error) {
584
+ if (error?.code !== 'binary-unsupported') throw error
585
+ // 二进制前像:**宿主有二进制写 seam 才写**(feature-detect,当前两线都没有)。
586
+ // 没有 ⇒ 显式 `failed/binary-unsupported`(不写乱码、也不假装成功)。
587
+ const writeBytes = typeof ctx.fs?.writeBytes === 'function' ? ctx.fs.writeBytes.bind(ctx.fs) : null
588
+ if (writeBytes === null) throw error
589
+ await writeBytes(row.target, bytes, expected, undefined, policy)
590
+ artifacts.push({ path: row.path, status: 'restored', via: 'bytes' })
591
+ continue
592
+ }
593
+ await ctx.fs.writeText(row.target, text, expected, undefined, policy)
570
594
  artifacts.push({ path: row.path, status: 'restored' })
571
595
  } catch (error) {
572
596
  artifacts.push({ path: row.path, status: 'failed', reason: error?.code ?? 'write-failed' })
@@ -736,6 +760,20 @@ export function createCheckpointRestore({
736
760
  return { sessionId, checkpoints }
737
761
  }
738
762
 
763
+ /**
764
+ * **过期 pending 剪枝**(启动 / 定期 / 手动共用入口)。
765
+ * 判据在 `prunePending` 里:只删 `pending === true` 且超龄 —— 已提交记录
766
+ * 与新鲜 pending(正在进行的操作)一律不动;幂等(没东西可删就是 0)。
767
+ * @returns {Promise<{sessions:number, removed:number}>}
768
+ */
769
+ async function pruneStalePending({ maxAgeMs = CHECKPOINT_PENDING_MAX_AGE_MS } = {}) {
770
+ const result = await preimages.pruneAllPending({ maxAgeMs, at: now() })
771
+ if (result.removed > 0) {
772
+ log(`retrace: pending 剪枝 → 清理 ${result.removed} 条超龄 pending(扫描 ${result.sessions} 个会话索引)`)
773
+ }
774
+ return result
775
+ }
776
+
739
777
  /** GC = checkpoint refs + live undo tickets + artifact-store refCounts (never delete a pinned object). */
740
778
  async function collectGarbage({ extraKeep = [] } = {}) {
741
779
  let artifactRefs = []
@@ -764,6 +802,7 @@ export function createCheckpointRestore({
764
802
  preview: envelope((args) => previewCheckpoint(String(args?.sessionId ?? ''), String(args?.versionId ?? ''))),
765
803
  execute: envelope((args) => executeCheckpoint(args)),
766
804
  collectGarbage,
805
+ pruneStalePending,
767
806
  pruneTickets: () => { for (const [key, ticket] of tickets) if (ticket.expires <= now()) tickets.delete(key) },
768
807
  }
769
808
  }
package/lib/index.js CHANGED
@@ -25,7 +25,7 @@ import { createRetraceHttpHandler, ROUTE_PREFIX } from './http.js'
25
25
  import { createVersioningSeam } from './versioning.js'
26
26
  import { createRollbackExecutor, createTrueRestore } from './rollback.js'
27
27
  import { createPreimageStore } from './preimage-store.js'
28
- import { createCheckpointRestore } from './checkpoint-restore.js'
28
+ import { createCheckpointRestore, CHECKPOINT_PENDING_PRUNE_INTERVAL_MS } from './checkpoint-restore.js'
29
29
  import { createMarkerGuard } from './prewrite-guard.js'
30
30
  import { createWatchdog } from './watchdog.js'
31
31
  import { createBootPinRetry } from './boot-pin.js'
@@ -46,6 +46,11 @@ import { readFileSync, existsSync, readdirSync, writeFileSync, renameSync, mkdir
46
46
  import { homedir } from 'node:os'
47
47
  import { join } from 'node:path'
48
48
  import { sessionFilePath, extraSessionBases } from './platform/session-paths.js'
49
+ // public build: 谱系标识生成/写标题一律关闭(只读接口保留)
50
+ const privateCodesEnabled = () => false
51
+
52
+ // public build: 无本版码概念 ⇒ 清理时不保留任何前缀(恒空串,避免引用未声明符号)
53
+ function ownCodeOf() { return '' }
49
54
  async function sessionBadge() { return '' }
50
55
  function syncBadge() { return '' }
51
56
  /**
@@ -79,7 +84,7 @@ export function trueTitleOf(session) {
79
84
  * @param {{log?: (line:string)=>void}} [hooks]
80
85
  * @returns {{dir: string|null, scanned: number, updated: number, failed: number}}
81
86
  */
82
- export function scrubProjcacheTitles({ log = null } = {}) {
87
+ export function scrubProjcacheTitles({ log = null, keepCodeOf = () => '' } = {}) {
83
88
  const result = { dir: null, scanned: 0, updated: 0, failed: 0 }
84
89
  const say = typeof log === 'function' ? log : () => {}
85
90
  let dir = null
@@ -110,7 +115,10 @@ export function scrubProjcacheTitles({ log = null } = {}) {
110
115
  const title = row?.record?.rows?.title
111
116
  if (title === null || typeof title !== 'object' || typeof title.val !== 'string') continue
112
117
  result.scanned += 1
113
- const clean = stripTitlePrefix(title.val)
118
+ // 文件名 = 会话 id(`<id>.json` 或 `session-<id>.json`)⇒ 用它取"本版自己的码"并保留
119
+ const sessionId = name.replace(/\.json$/, '').replace(/^session-/, '')
120
+ const keep = keepCodeOf(sessionId) || keepCodeOf(name.replace(/\.json$/, ''))
121
+ const clean = stripTitlePrefix(title.val, keep)
114
122
  if (clean === title.val) continue
115
123
  try {
116
124
  title.val = clean
@@ -131,10 +139,17 @@ export function scrubProjcacheTitles({ log = null } = {}) {
131
139
  * 纯函数:只做字符串判定,不写任何会话内容;清理路径用它得到"原标题"。
132
140
  * 不改生成规则、不解析前缀含义(对外不暴露实现细节)。
133
141
  */
134
- export function stripTitlePrefix(title) {
142
+ export function stripTitlePrefix(title, keepPrefix = '') {
135
143
  const text = String(title ?? '')
136
- const stripped = text.replace(/^(?:\[[^\]\s]{4,24}\]|【[^】\s]{4,24}】)\s*/, '')
137
- return stripped === text ? text : stripped
144
+ // 前缀形态:ASCII `[id]` 或全角 `【id】`(4..24 可见字符)
145
+ const match = /^(?:\[([^\]\s]{4,24})\]|【([^】\s]{4,24})】)\s*/.exec(text)
146
+ if (match === null) return text
147
+ const prefix = match[1] ?? match[2]
148
+ // **保留本版自己的码**:私有构建默认把 `[码]` 写回标题;清理只针对"未知/旧格式前缀",
149
+ // 否则每次启动都会把自己刚写的码剥掉(issue#7 清理与本版写入的顺序冲突)。
150
+ const keep = String(keepPrefix ?? '')
151
+ if (keep !== '' && prefix === keep) return text
152
+ return text.slice(match[0].length)
138
153
  }
139
154
 
140
155
  /**
@@ -144,12 +159,13 @@ export function stripTitlePrefix(title) {
144
159
  * 页点「清理标题旧前缀」的显式动作,走 op `restoreSessionTitles`)。纯函数,便于单测:
145
160
  * 传入 sessions 与 titleOf,返回 {scanned, prefixed}。
146
161
  */
147
- export function titlePrefixAudit(sessions, { titleOf = trueTitleOf } = {}) {
162
+ export function titlePrefixAudit(sessions, { titleOf = trueTitleOf, keepCodeOf = () => '' } = {}) {
148
163
  const list = Array.isArray(sessions) ? sessions : []
149
164
  let prefixed = 0
150
165
  for (const session of list) {
151
166
  const current = titleOf(session)
152
- if (stripTitlePrefix(current) !== current) prefixed += 1
167
+ const keep = keepCodeOf(session?.id ?? session?.sessionId ?? '')
168
+ if (stripTitlePrefix(current, keep) !== current) prefixed += 1
153
169
  }
154
170
  return { scanned: list.length, prefixed }
155
171
  }
@@ -566,7 +582,8 @@ export function apply(ctx) {
566
582
  */
567
583
  function cleanLiveTitle(session, label = '') {
568
584
  const current = trueTitleOf(session)
569
- const stripped = stripTitlePrefix(current)
585
+ // 私有构建默认把 `[码]` 写回标题 ⇒ 清理要**保留本版自己的码**,只清未知/旧格式前缀
586
+ const stripped = stripTitlePrefix(current, ownCodeOf(session?.id ?? session?.sessionId))
570
587
  if (stripped === current) return 'skipped'
571
588
  // 失败要可见:rename 抛错(会话非活/服务未挂载/标题非法)都留一条带上下文的日志
572
589
  const titles = ctx.get?.('sessionTitle')
@@ -616,7 +633,7 @@ export function apply(ctx) {
616
633
  const cap = Number(process.env.DSH_RETRACE_AUTO_CLEAN_MAX ?? 300)
617
634
  let handled = 0
618
635
  for (const [id, title] of cachedSessionTitles(liveIds)) {
619
- if (stripTitlePrefix(title) === title) { skipped += 1; continue }
636
+ if (stripTitlePrefix(title, ownCodeOf(id)) === title) { skipped += 1; continue }
620
637
  if (!(handled < cap)) { pending += 1; continue } // 超单轮上限 ⇒ 留给下一轮/打开时
621
638
  handled += 1
622
639
  const outcome = await cleanColdTitle(id)
@@ -631,7 +648,8 @@ export function apply(ctx) {
631
648
  }
632
649
  // ③ **投影缓存(侧栏读的就是它)**:官方 rename 只改会话日志,不回写 projcache
633
650
  // ⇒ 要把 title 行一起清掉,否则侧栏永远显示旧前缀(真机 114 个)。
634
- const cache = scrubProjcacheTitles({ log })
651
+ // ②b **私有构建默认开**:清理**之后**把 `[码] 标题` 写回驻留会话(顺序见下)。
652
+ const cache = scrubProjcacheTitles({ log, keepCodeOf: ownCodeOf })
635
653
  const summaryLine = `retrace: 启动标题自动清理完成 → 已清理 ${restored} / 跳过 ${skipped} / 失败 ${failed}`
636
654
  + `(未驻留剩余 ${pending}${unreadable > 0 ? `,日志不可读 ${unreadable}` : ''}`
637
655
  + `;投影缓存 title 行 ${cache.updated}/${cache.scanned} 已更新${cache.failed > 0 ? `,失败 ${cache.failed}` : ''})`
@@ -685,7 +703,7 @@ export function apply(ctx) {
685
703
  // (宿主只接受活会话时会抛 ⇒ 计入 pending,不猜、更不直接写人家的日志/缓存)。
686
704
  for (const [id, title] of cachedTitles) {
687
705
  scanned += 1
688
- const stripped = stripTitlePrefix(title)
706
+ const stripped = stripTitlePrefix(title, ownCodeOf(id))
689
707
  if (stripped === title) { skipped += 1; continue }
690
708
  let wrote = false
691
709
  try {
@@ -696,7 +714,7 @@ export function apply(ctx) {
696
714
  pending += 1
697
715
  if (pendingSample.length < 5) pendingSample.push(id)
698
716
  }
699
- const cache = scrubProjcacheTitles({ log })
717
+ const cache = scrubProjcacheTitles({ log, keepCodeOf: ownCodeOf })
700
718
  logOnce(`restoreSessionTitles:${scanned}:${restored}:${pending}:${cache.updated}`,
701
719
  `retrace: restoreSessionTitles → scanned=${scanned}(驻留 ${sessions.length} + 未驻留 ${cachedTitles.size}) restored=${restored} skipped=${skipped} pending=${pending} failed=${failed};投影缓存 title 行 ${cache.updated}/${cache.scanned} 已更新`)
702
720
  return { ok: true, value: { scanned, restored, skipped, failed, pending, pendingSample, cacheUpdated: cache.updated, cacheScanned: cache.scanned } }
@@ -879,6 +897,14 @@ export function apply(ctx) {
879
897
  logOnce(`autoCleanTitles:startup:${result.restored}:${result.skipped}:${result.failed}`,
880
898
  `retrace: 启动标题自动清理完成 → 已清理 ${result.restored} / 跳过 ${result.skipped} / 失败 ${result.failed}(未驻留剩余 ${result.pending})`)
881
899
  })
900
+ // 启动维护之二:清理**超龄 pending** 检查点(崩溃残留)。只删 pending 且超龄 ⇒
901
+ // 已提交记录与正在进行的 pending 不动(判据在 lib/preimage-store.js#prunePending)。
902
+ .then(async () => {
903
+ if (typeof checkpointRestore.pruneStalePending !== 'function') return
904
+ const pruned = await checkpointRestore.pruneStalePending()
905
+ logOnce(`prunePending:startup:${pruned.removed}`,
906
+ `retrace: 启动 pending 剪枝 → 清理 ${pruned.removed} 条超龄 pending(扫描 ${pruned.sessions} 个会话索引)`)
907
+ })
882
908
  .catch((error) => log(`retrace: 启动标题自动清理异常(可见,不影响主功能): ${String(error?.message ?? error).slice(0, 120)}`))
883
909
  }, 1200)
884
910
  if (typeof autoCleanTimer?.unref === 'function') autoCleanTimer.unref()
@@ -886,9 +912,24 @@ export function apply(ctx) {
886
912
  log(`retrace: 启动标题自动清理调度失败(可见): ${String(error?.message ?? error).slice(0, 120)}`)
887
913
  }
888
914
 
915
+ // 定期维护:每 6h 剪一次超龄 pending(懒清理只覆盖"被点开的会话",崩溃残留靠这里兜底)。
916
+ let pendingPruneTimer = null
917
+ try {
918
+ pendingPruneTimer = setInterval(() => {
919
+ if (typeof checkpointRestore.pruneStalePending !== 'function') return
920
+ checkpointRestore.pruneStalePending()
921
+ .then((pruned) => { if (pruned.removed > 0) logOnce(`prunePending:tick:${pruned.removed}`, `retrace: 定期 pending 剪枝 → 清理 ${pruned.removed} 条超龄 pending(扫描 ${pruned.sessions} 个会话索引)`) })
922
+ .catch((error) => log(`retrace: 定期 pending 剪枝失败(可见,不影响主功能): ${String(error?.message ?? error).slice(0, 120)}`))
923
+ }, CHECKPOINT_PENDING_PRUNE_INTERVAL_MS)
924
+ if (typeof pendingPruneTimer?.unref === 'function') pendingPruneTimer.unref()
925
+ } catch (error) {
926
+ log(`retrace: 定期 pending 剪枝调度失败(可见): ${String(error?.message ?? error).slice(0, 120)}`)
927
+ }
928
+
889
929
  const disposers = [
890
930
  () => sessionCreatedDispose?.(),
891
931
  () => { if (autoCleanTimer !== null) { try { clearTimeout(autoCleanTimer) } catch { /* 已触发 */ } autoCleanTimer = null } },
932
+ () => { if (pendingPruneTimer !== null) { try { clearInterval(pendingPruneTimer) } catch { /* 已触发 */ } pendingPruneTimer = null } },
892
933
 
893
934
  // recall 语义 = 遮蔽目标轮及之后全部(编辑=从此处分叉)
894
935
  // ——不再只遮蔽目标轮(缺陷①断层);tail 在官方 foldSurface
@@ -228,6 +228,35 @@ export function createPreimageStore({
228
228
  return removed
229
229
  }
230
230
 
231
+ /**
232
+ * Prune stale `pending` records for **every known session** (crash leftovers).
233
+ *
234
+ * 为什么需要"全量"版本:`prunePending(sessionId)` 只在用户**打开某个会话的**
235
+ * 读档/预览时才跑(懒清理)⇒ 崩溃残留会一直躺在盘上直到那个会话被点开。
236
+ * 启动/定期维护走这里(枚举 `checkpoints/*.json`,逐个调用同一实现,
237
+ * 判据不变:只删 `pending===true` 且超龄的记录 —— 已提交记录与新鲜 pending 一律不动)。
238
+ * @returns {Promise<{sessions:number, removed:number}>}
239
+ */
240
+ async function pruneAllPending({ maxAgeMs = 24 * 60 * 60 * 1000, at = now() } = {}) {
241
+ let names = []
242
+ try { names = await readdir(checkpointsRoot) } catch { return { sessions: 0, removed: 0 } }
243
+ let sessions = 0
244
+ let removed = 0
245
+ for (const name of names) {
246
+ if (!name.endsWith('.json')) continue
247
+ try {
248
+ const parsed = JSON.parse(await readFile(join(checkpointsRoot, name), 'utf8'))
249
+ const sessionId = typeof parsed?.sessionId === 'string' && parsed.sessionId !== '' ? parsed.sessionId : null
250
+ if (sessionId === null) continue
251
+ sessions += 1
252
+ removed += await prunePending(sessionId, { maxAgeMs, at })
253
+ } catch (error) {
254
+ log(`retrace: pending 剪枝跳过不可读的检查点索引(${name}): ${String(error)}`)
255
+ }
256
+ }
257
+ return { sessions, removed }
258
+ }
259
+
231
260
  /** Refuse to collect while another append is mid-flight in this process. */
232
261
  async function settled() {
233
262
  await Promise.all([...tails.values()])
@@ -303,6 +332,7 @@ export function createPreimageStore({
303
332
  updateRecord,
304
333
  removeRecord,
305
334
  prunePending,
335
+ pruneAllPending,
306
336
  retain,
307
337
  collect,
308
338
  now,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-retrace",
3
3
  "description": "Retrace · 回溯 — Recall, edit-and-resend, regenerate, and conversation/artifact versioning (timeline, rollback, fork graph) for DeepSeek Harness — Web and Desktop",
4
- "version": "0.4.150",
4
+ "version": "0.4.152",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -69,8 +69,8 @@
69
69
  },
70
70
  "target": {
71
71
  "package": "dsh-retrace",
72
- "version": "0.4.150",
73
- "host": ">=0.1.5 <0.3.0"
72
+ "version": "0.4.152",
73
+ "host": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0"
74
74
  },
75
75
  "changes": [
76
76
  "http: require a loopback socket peer plus a same-origin Host/Origin gate; non-loopback peer, forged Host or bad Origin => 403 fail-closed",
@@ -94,7 +94,7 @@
94
94
  "platform": "web"
95
95
  },
96
96
  "compatibility": {
97
- "dsh": ">=0.1.5 <0.3.0",
97
+ "dsh": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
98
98
  "node": ">=20.0.0",
99
99
  "modes": [
100
100
  "desktop",
@@ -104,13 +104,14 @@
104
104
  },
105
105
  "peerDependencies": {
106
106
  "@deepseek-ai/cordis": "^4.0.0",
107
- "@deepseek-ai/dsh-client-locale": ">=0.1.7-rc.2 <0.3.0",
108
- "@deepseek-ai/dsh-client-ui-conversation": ">=0.1.7-rc.2 <0.3.0",
109
- "@deepseek-ai/dsh-client-ui-slots": ">=0.1.7-rc.2 <0.3.0",
110
- "@deepseek-ai/dsh-session": ">=0.1.7-rc.2 <0.3.0",
111
- "@deepseek-ai/dsh-storage-domain": ">=0.1.7-rc.2 <0.3.0",
112
- "@deepseek-ai/dsh-token-meter": ">=0.1.7-rc.2 <0.3.0",
113
- "react": "^18.2.0"
107
+ "@deepseek-ai/dsh-client-locale": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
108
+ "@deepseek-ai/dsh-client-ui-conversation": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
109
+ "@deepseek-ai/dsh-client-ui-slots": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
110
+ "@deepseek-ai/dsh-session": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
111
+ "@deepseek-ai/dsh-storage-domain": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
112
+ "@deepseek-ai/dsh-token-meter": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
113
+ "react": "^18.2.0",
114
+ "@deepseek-ai/dsh-compaction-basic": ">=0.1.7-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0"
114
115
  },
115
116
  "dependencies": {
116
117
  "dsh-log-contract": "^0.3.18",
@@ -133,5 +134,10 @@
133
134
  },
134
135
  "engines": {
135
136
  "node": ">=20.0.0"
137
+ },
138
+ "peerDependenciesMeta": {
139
+ "@deepseek-ai/dsh-compaction-basic": {
140
+ "optional": true
141
+ }
136
142
  }
137
143
  }