dsh-retrace 0.4.151 → 0.4.153

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.151 is the current release** — install/pin `0.4.151` (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.151` examples below apply to this release.
38
+ > **0.4.153 is the current release** — install/pin `0.4.153` (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.153` 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.151"
156
+ "dsh-retrace": "^0.4.153"
157
157
  },
158
158
  "dsh": {
159
159
  "profile": {
@@ -354,7 +354,7 @@ Historical details and exact error strings live in [CHANGELOG.md](./CHANGELOG.md
354
354
  ### Upgrading
355
355
 
356
356
  ```bash
357
- dsh plugin --profile desktop add dsh-retrace@0.4.151
357
+ dsh plugin --profile desktop add dsh-retrace@0.4.153
358
358
  # then restart DSH — plugins are not hot-reloaded
359
359
  ```
360
360
 
@@ -378,7 +378,7 @@ whole tree down, so recover first and diagnose second:
378
378
 
379
379
  ### Pinning
380
380
 
381
- Pin an exact plugin version (`dsh-retrace@0.4.151`) and let `dsh-log-contract` resolve to
381
+ Pin an exact plugin version (`dsh-retrace@0.4.153`) and let `dsh-log-contract` resolve to
382
382
  `>=0.3.18`. Do not rely on `^0.4` across a host upgrade: compatibility here is decided by
383
383
  the **host surface**, not by semver alone.
384
384
 
package/README.zh.md CHANGED
@@ -30,7 +30,7 @@
30
30
 
31
31
  > 版本索引:[VERSIONS.md](./VERSIONS.md)
32
32
 
33
- > **0.4.151 为当前版本**——安装/固定请用 `0.4.151`(**GitHub Release 已发,npm 待发**;npm 最新可安装版本仍为 `0.4.139`,见 [VERSIONS.md](./VERSIONS.md));下文的 `dsh-retrace@0.4.151` 示例适用于该版本。
33
+ > **0.4.153 为当前版本**——安装/固定请用 `0.4.153`(**GitHub Release 已发,npm 待发**;npm 最新可安装版本仍为 `0.4.139`,见 [VERSIONS.md](./VERSIONS.md));下文的 `dsh-retrace@0.4.153` 示例适用于该版本。
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.151"
140
+ "dsh-retrace": "^0.4.153"
141
141
  },
142
142
  "dsh": {
143
143
  "profile": {
@@ -315,7 +315,7 @@ Client 半区会依据包内 `dsh.client` 元数据被自动打包进 Web 客户
315
315
  ### 升级
316
316
 
317
317
  ```bash
318
- dsh plugin --profile desktop add dsh-retrace@0.4.151
318
+ dsh plugin --profile desktop add dsh-retrace@0.4.153
319
319
  # 然后重启 DSH —— 插件不会热重载
320
320
  ```
321
321
 
@@ -334,7 +334,7 @@ dsh plugin --profile desktop add dsh-retrace@0.4.151
334
334
 
335
335
  ### 版本固定建议
336
336
 
337
- 请固定到确切版本(`dsh-retrace@0.4.151`),并让 `dsh-log-contract` 解析到 `>=0.3.18`。
337
+ 请固定到确切版本(`dsh-retrace@0.4.153`),并让 `dsh-log-contract` 解析到 `>=0.3.18`。
338
338
  **不要在跨宿主升级时依赖 `^0.4` 这种范围**:这里的兼容性由**宿主的面**决定,光看 semver 不够。
339
339
 
340
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
 
@@ -253,6 +263,50 @@ export function turnAtSeq(events, seq) {
253
263
  return null
254
264
  }
255
265
 
266
+ /**
267
+ * 轮次索引:`seq → 该处及之前最近的正 turn`,一次扫描建表(升序起点 seqs + 对应 turns)。
268
+ *
269
+ * 为什么需要:`turnAtSeq` 是**向后线性扫**,而 `restoreList` 对每条读档点/检查点都
270
+ * 各调一次(最多 200 + 200 次)。在 7.5 万事件、turn 稀疏的真实会话上实测 400 次
271
+ * ≈ 46ms,占 restoreList 的 ~80%;索引把每次查询降到 O(log n),语义与 `turnAtSeq`
272
+ * **逐值一致**(由 test/checkpoint-restore.test.js 的等价用例钉住,不含近似)。
273
+ * @param {Array<object>} events
274
+ * @returns {{seqs:number[], turns:number[]}}
275
+ */
276
+ export function buildTurnIndex(events) {
277
+ const list = Array.isArray(events) ? events : []
278
+ const seqs = []
279
+ const turns = []
280
+ for (let i = 0; i < list.length; i += 1) {
281
+ const turn = list[i]?.data?.turn
282
+ if (Number.isSafeInteger(turn) && turn > 0) { seqs.push(i); turns.push(turn) }
283
+ }
284
+ return { seqs, turns }
285
+ }
286
+
287
+ /**
288
+ * 索引版 `turnAtSeq`:返回 `seq`(含)之前最近的正 turn;没有则 null。
289
+ * @param {{seqs:number[], turns:number[]}} index - buildTurnIndex 的产物
290
+ * @param {number} seq
291
+ * @param {number} [length] - 事件总数(用于把越界 seq 夹到最后一条)
292
+ * @returns {number|null}
293
+ */
294
+ export function turnAtIndex(index, seq, length) {
295
+ const seqs = Array.isArray(index?.seqs) ? index.seqs : []
296
+ const turns = Array.isArray(index?.turns) ? index.turns : []
297
+ if (seqs.length === 0) return null
298
+ const last = Number.isSafeInteger(length) && length > 0 ? length - 1 : seqs[seqs.length - 1]
299
+ const target = Math.min(Number.isSafeInteger(seq) ? seq : last, last)
300
+ let lo = 0
301
+ let hi = seqs.length - 1
302
+ let hit = -1
303
+ while (lo <= hi) {
304
+ const mid = (lo + hi) >> 1
305
+ if (seqs[mid] <= target) { hit = mid; lo = mid + 1 } else { hi = mid - 1 }
306
+ }
307
+ return hit >= 0 ? turns[hit] : null
308
+ }
309
+
256
310
  /**
257
311
  * Merge readpoints (operation boundaries) and checkpoint preimages into ONE
258
312
  * restore list (newest first: turn desc, then time desc). Pure so the ordering
@@ -427,8 +481,9 @@ export function createCheckpointRestore({
427
481
 
428
482
  async function previewCheckpoint(sessionId, versionId) {
429
483
  const session = sessionOf(sessionId)
430
- await preimages.prunePending(sessionId, { maxAgeMs: CHECKPOINT_PENDING_MAX_AGE_MS, at: now() })
431
- const records = await preimages.records(sessionId)
484
+ // 剪枝与读取共用**一次**索引读取(同一判据;无 stale 时不写盘)
485
+ const pruned = await preimages.prunePendingAndRecords(sessionId, { maxAgeMs: CHECKPOINT_PENDING_MAX_AGE_MS, at: now() })
486
+ const records = pruned.records
432
487
  const record = records.find((candidate) => candidate.versionId === versionId)
433
488
  if (!record) throw editorError('version-not-found', `checkpoint "${versionId}" not found in session "${sessionId}"`)
434
489
  const events = sessionEvents(session)
@@ -564,9 +619,23 @@ export function createCheckpointRestore({
564
619
  artifacts.push({ path: row.path, status: 'deleted' })
565
620
  continue
566
621
  }
567
- const text = textOf(await preimages.objectStore.read(row.sha256))
622
+ const bytes = await preimages.objectStore.read(row.sha256)
568
623
  const policy = ctx.sandboxPolicy?.resolve?.({ session })
569
- await ctx.fs.writeText(row.target, text, row.version === null ? { kind: 'createIfAbsent' } : replaceIfVersion(row.version), undefined, policy)
624
+ const expected = row.version === null ? { kind: 'createIfAbsent' } : replaceIfVersion(row.version)
625
+ let text = null
626
+ try {
627
+ text = textOf(bytes)
628
+ } catch (error) {
629
+ if (error?.code !== 'binary-unsupported') throw error
630
+ // 二进制前像:**宿主有二进制写 seam 才写**(feature-detect,当前两线都没有)。
631
+ // 没有 ⇒ 显式 `failed/binary-unsupported`(不写乱码、也不假装成功)。
632
+ const writeBytes = typeof ctx.fs?.writeBytes === 'function' ? ctx.fs.writeBytes.bind(ctx.fs) : null
633
+ if (writeBytes === null) throw error
634
+ await writeBytes(row.target, bytes, expected, undefined, policy)
635
+ artifacts.push({ path: row.path, status: 'restored', via: 'bytes' })
636
+ continue
637
+ }
638
+ await ctx.fs.writeText(row.target, text, expected, undefined, policy)
570
639
  artifacts.push({ path: row.path, status: 'restored' })
571
640
  } catch (error) {
572
641
  artifacts.push({ path: row.path, status: 'failed', reason: error?.code ?? 'write-failed' })
@@ -672,8 +741,15 @@ export function createCheckpointRestore({
672
741
  async function listUnified(args) {
673
742
  const sessionId = String(args?.sessionId ?? '')
674
743
  const session = sessionOf(sessionId)
675
- await preimages.prunePending(sessionId, { maxAgeMs: CHECKPOINT_PENDING_MAX_AGE_MS, at: now() })
744
+ const prunedCheckpoints = await preimages.prunePendingAndRecords(sessionId, { maxAgeMs: CHECKPOINT_PENDING_MAX_AGE_MS, at: now() })
676
745
  const events = sessionEvents(session)
746
+ // 懒建索引:一次扫描建表,替代逐条向后线性扫(见 buildTurnIndex 的注释)。
747
+ // 只有真有读档点/检查点时才付建表成本(空列表 ⇒ 零成本)。
748
+ let turnIndex = null
749
+ const turnOf = (seq) => {
750
+ if (turnIndex === null) turnIndex = buildTurnIndex(events)
751
+ return turnAtIndex(turnIndex, seq, events.length)
752
+ }
677
753
  const snapshot = typeof seam?.snapshot === 'function' ? seam.snapshot(sessionId) : { versions: [] }
678
754
  const readpoints = (snapshot?.versions ?? [])
679
755
  .filter((version) => version && version.kind !== 'replace')
@@ -683,7 +759,7 @@ export function createCheckpointRestore({
683
759
  kind: version.kind,
684
760
  boundarySeq: version.boundarySeq,
685
761
  createdAt: version.createdAt,
686
- turn: turnAtSeq(events, version.boundarySeq),
762
+ turn: turnOf(version.boundarySeq),
687
763
  messageCount: Number.isSafeInteger(version.messageCount) ? version.messageCount : 0,
688
764
  markerText: typeof version.markerText === 'string' ? version.markerText : '',
689
765
  fileCount: Array.isArray(version.touchedFiles) ? version.touchedFiles.length : 0,
@@ -693,13 +769,13 @@ export function createCheckpointRestore({
693
769
  pending: false,
694
770
  warnings: [],
695
771
  }))
696
- const checkpoints = (await preimages.records(sessionId)).map((record) => ({
772
+ const checkpoints = prunedCheckpoints.records.map((record) => ({
697
773
  id: record.versionId,
698
774
  versionId: record.versionId,
699
775
  kind: 'preimage',
700
776
  boundarySeq: record.cutSeq,
701
777
  createdAt: record.createdAt,
702
- turn: turnAtSeq(events, record.cutSeq),
778
+ turn: turnOf(record.cutSeq),
703
779
  messageCount: record.cutSeq + 1,
704
780
  markerText: '',
705
781
  fileCount: record.files.length,
@@ -720,8 +796,8 @@ export function createCheckpointRestore({
720
796
  */
721
797
  async function listCheckpoints(sessionId) {
722
798
  sessionOf(sessionId)
723
- await preimages.prunePending(sessionId, { maxAgeMs: CHECKPOINT_PENDING_MAX_AGE_MS, at: now() })
724
- const records = await preimages.records(sessionId)
799
+ const pruned = await preimages.prunePendingAndRecords(sessionId, { maxAgeMs: CHECKPOINT_PENDING_MAX_AGE_MS, at: now() })
800
+ const records = pruned.records
725
801
  const checkpoints = records.slice().reverse().map((record) => ({
726
802
  versionId: record.versionId,
727
803
  kind: record.kind,
@@ -736,6 +812,20 @@ export function createCheckpointRestore({
736
812
  return { sessionId, checkpoints }
737
813
  }
738
814
 
815
+ /**
816
+ * **过期 pending 剪枝**(启动 / 定期 / 手动共用入口)。
817
+ * 判据在 `prunePending` 里:只删 `pending === true` 且超龄 —— 已提交记录
818
+ * 与新鲜 pending(正在进行的操作)一律不动;幂等(没东西可删就是 0)。
819
+ * @returns {Promise<{sessions:number, removed:number}>}
820
+ */
821
+ async function pruneStalePending({ maxAgeMs = CHECKPOINT_PENDING_MAX_AGE_MS } = {}) {
822
+ const result = await preimages.pruneAllPending({ maxAgeMs, at: now() })
823
+ if (result.removed > 0) {
824
+ log(`retrace: pending 剪枝 → 清理 ${result.removed} 条超龄 pending(扫描 ${result.sessions} 个会话索引)`)
825
+ }
826
+ return result
827
+ }
828
+
739
829
  /** GC = checkpoint refs + live undo tickets + artifact-store refCounts (never delete a pinned object). */
740
830
  async function collectGarbage({ extraKeep = [] } = {}) {
741
831
  let artifactRefs = []
@@ -764,6 +854,7 @@ export function createCheckpointRestore({
764
854
  preview: envelope((args) => previewCheckpoint(String(args?.sessionId ?? ''), String(args?.versionId ?? ''))),
765
855
  execute: envelope((args) => executeCheckpoint(args)),
766
856
  collectGarbage,
857
+ pruneStalePending,
767
858
  pruneTickets: () => { for (const [key, ticket] of tickets) if (ticket.expires <= now()) tickets.delete(key) },
768
859
  }
769
860
  }
package/lib/client-css.js CHANGED
@@ -72,6 +72,15 @@ export const CSS = `
72
72
  .dsh-rt-reference[open] summary:before{transform:rotate(90deg)}
73
73
  .dsh-rt-reference summary:hover{color:var(--dsw-alias-label-secondary)}
74
74
  .dsh-rt-reference-text{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;white-space:pre-wrap;overflow-wrap:anywhere;padding:2px 0 6px}
75
+ .dsh-rt-restore-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:2px 0 6px}
76
+ .dsh-rt-search{flex:1 1 180px;min-width:140px;box-sizing:border-box;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-elevated);border:1px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);font:inherit;padding:2px 8px}
77
+ .dsh-rt-filter{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-elevated);border:1px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);font:inherit;font-size:12px;padding:2px 4px}
78
+ .dsh-rt-select-box{width:16px;height:16px;margin:0 4px 0 0;cursor:pointer;accent-color:var(--dsw-alias-state-business-primary)}
79
+ .dsh-rt-turn-group{position:absolute;left:0;right:0;height:28px;display:flex;align-items:center;gap:8px;padding:0 4px}
80
+ .dsh-rt-turn-head{cursor:pointer;color:var(--dsw-alias-label-secondary);background:transparent;border:none;font:inherit;font-size:12px;padding:2px 6px;border-radius:var(--dsw-radius-sm)}
81
+ .dsh-rt-turn-head:hover{background:var(--dsw-alias-interactive-bg-hover)}
82
+ .dsh-rt-branch-1{box-shadow:inset 2px 0 0 var(--dsw-alias-label-secondary)}
83
+ .dsh-rt-branch-2{box-shadow:inset 2px 0 0 var(--dsw-alias-state-warning-primary)}
75
84
  .dsh-rt-options{display:flex;flex-direction:column;gap:8px;padding:2px 0}
76
85
  .dsh-rt-options-title{color:var(--dsw-alias-label-secondary);font-size:13px;font-weight:600;line-height:20px}
77
86
  .dsh-rt-option{display:flex;align-items:center;gap:8px;color:var(--dsw-alias-label-secondary);font-size:13px;line-height:20px;cursor:pointer}
@@ -143,6 +143,13 @@ export const zh = {
143
143
  'timeline.kind.preimage': '操作前快照',
144
144
  'restore.orderHint': '最近的改动在最上面',
145
145
  'restore.loadMore': '加载更多',
146
+ // P2-a 读档点骨架/搜索/多选导出(对外只描述用法,不暴露内部机制)。
147
+ 'restore.groupTurn': '第 {turn} 轮 · {count} 条',
148
+ 'restore.searchPlaceholder': '搜索轮次或关键词',
149
+ 'restore.kindAll': '全部',
150
+ 'restore.selectAll': '全选',
151
+ 'restore.exportSelected': '导出 {count} 条',
152
+ 'restore.emptyFiltered': '没有匹配的读档点',
146
153
  'restore.preimageLine': '操作前快照 · {count} 个文件',
147
154
  'restore.fileMark': '可回退文件',
148
155
  'restore.fileMarkHint': '该条目带文件前像,回档时一并恢复文件',
@@ -441,6 +448,13 @@ export const en = {
441
448
  'timeline.kind.preimage': 'Pre-operation snapshot',
442
449
  'restore.orderHint': 'Newest changes are at the top',
443
450
  'restore.loadMore': 'Load more',
451
+ // P2-a restore skeleton/search/multi-select export.
452
+ 'restore.groupTurn': 'Round {turn} · {count} changes',
453
+ 'restore.searchPlaceholder': 'Search round or keyword',
454
+ 'restore.kindAll': 'All',
455
+ 'restore.selectAll': 'Select all',
456
+ 'restore.exportSelected': 'Export {count}',
457
+ 'restore.emptyFiltered': 'No matching restore points',
444
458
  'restore.preimageLine': 'Pre-operation snapshot · {count} file(s)',
445
459
  'restore.fileMark': 'Restorable files',
446
460
  'restore.fileMarkHint': 'This entry carries file preimages; rolling back also restores files',