dsh-retrace 0.4.134 → 0.4.139

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.
Files changed (48) hide show
  1. package/README.md +33 -108
  2. package/README.zh.md +30 -79
  3. package/bin/retrace.mjs +0 -0
  4. package/lib/adapter/compaction-backend.js +92 -0
  5. package/lib/adapter/contract.js +2 -2
  6. package/lib/adapter/dsh-writer.js +75 -1
  7. package/lib/adapter/dsh.js +504 -4
  8. package/lib/adapter/register-compaction-backend.js +93 -0
  9. package/lib/auto-fold-scheduler.js +519 -0
  10. package/lib/boundary-what.js +41 -4
  11. package/lib/cache-metrics.js +155 -0
  12. package/lib/client-css.js +24 -0
  13. package/lib/client-i18n.js +37 -10
  14. package/lib/client.bundle.js +26 -2
  15. package/lib/client.js +522 -52
  16. package/lib/close-guard-client.js +3 -3
  17. package/lib/close-guard.js +1 -1
  18. package/lib/context-level.js +139 -0
  19. package/lib/core-contract.js +77 -0
  20. package/lib/dynamic-client.js +26 -2
  21. package/lib/dynamic-host.js +895 -6
  22. package/lib/fold-auto.js +621 -0
  23. package/lib/fold-boundary.js +1000 -0
  24. package/lib/fold-core-text.js +52 -0
  25. package/lib/fold-core.js +191 -0
  26. package/lib/fold-summary.js +168 -0
  27. package/lib/git-adapter.js +133 -38
  28. package/lib/host-core.js +295 -3
  29. package/lib/http.js +131 -0
  30. package/lib/hw3-fallback.js +262 -0
  31. package/lib/identity/code-assign.js +228 -0
  32. package/lib/identity/dedupe.js +168 -0
  33. package/lib/identity/shortcode.js +124 -24
  34. package/lib/identity/sidebar-badge.js +58 -32
  35. package/lib/identity-check-cli.js +379 -0
  36. package/lib/index.js +602 -3
  37. package/lib/ledger-guard.js +491 -0
  38. package/lib/marker-carrier.js +24 -0
  39. package/lib/message-list.js +1 -1
  40. package/lib/prewrite-guard.js +33 -2
  41. package/lib/recall-index.js +247 -0
  42. package/lib/rollback.js +2 -2
  43. package/lib/span-semantics.js +190 -1
  44. package/lib/summary-gate.js +11 -6
  45. package/lib/token-estimate.js +91 -0
  46. package/lib/version-index.js +8 -5
  47. package/lib/versioning.js +13 -2
  48. package/package.json +8 -6
package/README.md CHANGED
@@ -33,6 +33,10 @@ it cannot dirty the log, and new markers create **no token-meter pairing debt**
33
33
 
34
34
  ---
35
35
 
36
+ > Versions: [VERSIONS.md](./VERSIONS.md)
37
+
38
+ > 0.4.139 is the current release — install/pin `0.4.139` (the previous npm latest was `0.4.135`; see [VERSIONS.md](./VERSIONS.md)); the `dsh-retrace@0.4.139` examples below apply after that release.
39
+
36
40
  ## ⚡ One-minute install
37
41
 
38
42
  > Requires DeepSeek Harness with the `dsh` CLI. **Restart DSH after install** (a running app does not hot-reload).
@@ -87,11 +91,12 @@ Full steps in [📦 Installation](#-installation).
87
91
  |---|---|---|
88
92
  | 🕘 | **Checkpoints** | a **Checkpoints** tab in the conversation view: every change (type, time, message count, file-change badges), pushed live via `session/projection` (no polling), windowed for long histories; nested history is browsable outline-style |
89
93
  | ↩️ | **Artifact rollback** | **context-only / artifacts-only / both** with dry-run preview; git-first + content-addressed snapshot fallback; a rollback is itself a new checkpoint (`restore`). Preview refuses while the agent is running (so "preview says yes, confirm says no" cannot happen), and preview/rollback failures are shown in the UI instead of failing silently |
94
+ | 🧬 | **Lineage identity** | every new session gets a stable lineage id automatically; the sidebar shows one badge per conversation (no duplicates on refresh) |
90
95
  | 🧭 | **Jump-to-conversation** | one click from a checkpoint to that point in the conversation (auto-loads history, anchor highlight); when the point is out of the auto-load budget the reason is reported instead of nothing happening |
91
96
  | 🧹 | **Bounded storage** | snapshots keep the most recent N checkpoints (default 50); throttled background sweep prunes truncated ones |
92
97
 
93
98
  > **Rollback on a damaged log** is not silent: the host's strict replay is the
94
- > authority, but a single malformed event (for example a `sourceEventSeqs` row
99
+ > authority, but a single malformed event (for example a malformed replace row
95
100
  > written by a third party with range encoding) can poison the whole replay. In
96
101
  > that case the rollback degrades to a mirror replay, logs both the degradation
97
102
  > and the original error, and flags the result as `degraded` on the wire; if even
@@ -146,7 +151,7 @@ The same result with plain file edits and `pnpm` — exactly the steps
146
151
  ```json
147
152
  {
148
153
  "dependencies": {
149
- "dsh-retrace": "^0.4.131"
154
+ "dsh-retrace": "^0.4.139"
150
155
  },
151
156
  "dsh": {
152
157
  "profile": {
@@ -215,7 +220,7 @@ The dynamic host registers the same operations behind the package-private
215
220
  - DeepSeek Harness providing the peer packages listed in `package.json`
216
221
  (`@deepseek-ai/dsh-session`, `@deepseek-ai/dsh-client-*`, `cordis`, `react` — the
217
222
  current build targets the `0.1.7-rc.2` generation).
218
- - `dsh-log-contract >= 0.3.12` (installed automatically as a dependency).
223
+ - `dsh-log-contract >= 0.3.18` (installed automatically as a dependency).
219
224
  - The plugin declares the host capabilities it needs via `inject`
220
225
  (`sessions`, `agents`, `webServer`, `fs`, `subprocess`, `sandboxPolicy`, `jobs`).
221
226
  A missing capability degrades the corresponding feature (for example, no
@@ -250,27 +255,12 @@ Before you exit or reload, know what is still running:
250
255
  > handler, or a pre-quit prompt hook). If the app cannot quit, turning off "Exit
251
256
  > confirmation (close guard)" recovers immediately (no restart).
252
257
 
253
- ### Session badge & display name (**planned / off by default**)
254
-
255
- Badges are for human collaboration; **identity is still decided by the session id**.
256
- The transports (`sessionBadge` / `setBadgeTitle` / `initBadgeTitles` / `badgeMap`,
257
- on both HTTP and harness), the resolver and the write guards are **in place**, but
258
- the **automatic startup path that writes titles is off by default** (the client
259
- gate is `globalThis.__DSH_RETRACE_BADGE_BOOTSTRAP = true`):
258
+ ### Session badge & display name
260
259
 
261
- - A session title renders as `[badge] original title` — the **stable identifier is
262
- derived deterministically from the session id**, so a title change never changes it.
263
- - Sessions with **no `session/title` event are left blank on purpose** (the title shows just
264
- `[badge]`) — **no project-name fallback, no fabricated name**.
265
- - If the resolver is unavailable it falls back to the **raw session id as a placeholder**.
266
- - The sidebar row, the running banner and the checkpoint view share **one source**: the same badge
267
- map the host hands down (host op `badgeMap`).
268
-
269
- > **Planned (not shipped)**: the agent business-layer plan (runtime guard,
270
- > interruption governance, ecosystem-facing interfaces) is a **plan**, not a
271
- > shipped capability.
272
-
273
- ---
260
+ - The sidebar shows **one badge per conversation**; the conversation title keeps the plain name. The stable identifier is **derived deterministically from the session id** (no random suffix).
261
+ - **There is no setting for this yet.** Two runtime switches exist:
262
+ - `DSH_RETRACE_SHOW_CODES=0` — hide lineage codes (host-side, takes effect on restart);
263
+ - Custom display names and a settings-page toggle are **planned** — see [docs/PLAN.md](./docs/PLAN.md) and [docs/ROADMAP.md](./docs/ROADMAP.md).
274
264
 
275
265
  ## ⚙️ Settings → General
276
266
 
@@ -347,90 +337,26 @@ the symptom is usually a failed boot, not a wrong-looking feature.
347
337
  This section exists so you can tell **host-side breakage** from **plugin-side bugs**.
348
338
  Read it before filing an issue.
349
339
 
350
- ### Host-side breaking changes this plugin adapts to — *not caused by this plugin*
351
-
352
- 1. **`@deepseek-ai/dsh-session` removed the `Session.events` member** (in `0.1.5-rc.1`).
353
- The supported readers are `snapshotEvents(fromSeq, toSeqExclusive)` (frozen,
354
- sequence-indexed), `eventAt(seq)`, `ownEvents()` and `isOwnSeq(seq)`. Before the
355
- fix, recall and edit did nothing and surfaced
356
- `TypeError: Cannot read properties of undefined (reading 'length')`. The plugin
357
- now reaches the log through a compatibility accessor that prefers the new API and
358
- falls back to the old array, so both host generations work.
359
- 2. **`@deepseek-ai/dsh-session` dropped `decodeStorageRecord` from its public export
360
- surface** (in `0.1.5-rc.1`; the function still exists internally but is no longer
361
- exported from the package root and is unreachable via the exports map).
362
- `dsh-retrace` itself never imported it, but its dependency `dsh-log-contract` did.
363
- With no such export the loader aborts with
364
- `plugin tree failed to load … does not provide an export named 'decodeStorageRecord'`
365
- and **the whole plugin tree fails to load — not just this plugin**, so the app does
366
- not start.
367
- → **Dependency note:** needs `dsh-log-contract >= 0.3.12`.
368
- 3. **A client **service** disappeared: `conversationEvents`** — it used to be provided by
369
- the legacy client runtime `@deepseek-ai/dsh-client-runtime`, which has been removed.
370
- A plugin whose client half still declares that service in `export const inject` never
371
- becomes ready: its fiber stays **pending**, which the host reports as
372
- `renderer boot failed (plugins: …): The client Loader did not provide an error message.`
373
- — no error text at all, the window does not finish starting, and the only way in is to
374
- disable the plugin. The plugin drops the service from `inject` and resolves it
375
- **defensively** in `apply` (`uiConversation`, falling back to the legacy name).
376
- > Note: declaring a **package** that no longer exists in `dsh.client.inject` is *not*
377
- > what breaks the boot — the client loader skips unknown entries silently. The
378
- > breakage comes from the **service name** the plugin waits for.
379
- 4. **The client-side session store has no `keys()`** (`ctx.sessions`). A plugin that
380
- enumerates sessions with `keys()` silently sees **zero** of them: no crash, no error,
381
- just safety warnings that never fire. The plugin prefers the official `list()` and
382
- falls back to `keys()`; it deliberately does **not** fall back to enumerating service
383
- fields, because guessing produces a silent empty result as well.
384
-
385
- > All four items are **host-side removals**, documented here on purpose: if you hit
386
- > one of these symptoms right after a host upgrade, the first question is "does this
387
- > plugin build predate the removal?", not "what did the plugin break?".
388
-
389
- ### Plugin-side fixes (0.4.26 – 0.4.28)
390
-
391
- - **Data home and session base are now one source.** The plugin previously resolved its
392
- own data directory through the host's home resolver (`$DSH_HOME` → `~/.dsh`), which
393
- does not know about extra bases configured through `$DSH_SESSION_BASES`. With
394
- `$DSH_HOME` unset, sessions were read from one base while snapshots and the artifact
395
- store were written to another. Snapshots,
396
- version stores and `verify-install` now follow the **active session base**. When
397
- `$DSH_HOME` is set, behaviour is unchanged.
398
- - **No user-visible string hard-codes `~/.dsh` any more** (the settings hint used to say
399
- snapshots live under `~/.dsh`).
400
- - **The edit / recall affordances never appeared at all.** The client half read chat
401
- nodes from `snapshot.chat.nodes`, a path this host build does not have — nodes live in
402
- the `useChat` store (`snapshot.nodes`). Every message-level component threw while
403
- rendering and was swallowed by the error boundary, so the buttons were missing, while
404
- the settings entry (which reads no nodes) rendered fine.
405
- - **"Jump to message" in the checkpoint view did nothing.** It resolved the target
406
- anchor through `store.getSnapshot()?.chat?.nodes`, which is permanently `undefined`
407
- here. It now resolves through the `useChat` snapshot injected by the view and pages
408
- with the official `store.loadThrough(seq)`; when the jump cannot complete it reports a
409
- **diagnosable reason** (renderer warning + host-log line) instead of failing silently.
410
- - **Assigning a lineage ID could overwrite your session title.** Title tagging now goes
411
- through the host route only (`setBadgeTitle`), which reads the current title from the
412
- session log. Manual renames are unaffected.
413
- - **Host-side operation failures are logged again** (code + message + stack). They used
414
- to return the message to the UI without a log line, which made this class of bug hard
415
- to diagnose from outside.
416
- - **The checkpoint view now explains itself.** It used to show a title plus a row of
417
- actions with **no sentence anywhere saying what a "checkpoint" is**, and rows printed
418
- raw node types. It now carries an always-visible concept sentence, a type legend, and
419
- a plain-language "why" line on every row.
420
- - **Client hide-lookup no longer rescans per row.** `useSeqHidden` re-scanned the node map
421
- for every row (measured **346 ms** at 2000 rows / 20 markers, **1568 ms** at 3000/30).
422
- It now reuses one per-snapshot hide plan: **8.3 ms** and **18.3 ms** respectively, with
423
- the predicate verified equivalent against the old one.
340
+ ### Host-side changes to be aware of
341
+
342
+ The host occasionally removes APIs this plugin relied on. These are **host-side changes, not plugin defects** — symptoms and one-line fixes:
343
+
344
+ - Boot loop / recovery screen after a host upgrade → switch to a clean session and restart DSH; the plugin falls back to degraded mode instead of blocking.
345
+ - Version/checkpoint panels empty after an upgrade → run `dsh plugin --profile <p> add dsh-retrace` to refresh the bundle.
346
+ - Title/rename behaves differently → automatic title bootstrap is guarded by the host; manual rename keeps working.
347
+ - Dependency floor: `dsh-log-contract >= 0.3.18`.
348
+
349
+ Historical details and exact error strings live in [CHANGELOG.md](./CHANGELOG.md); compatibility matrix in [docs/COMPAT.md](./docs/COMPAT.md).
424
350
 
425
351
  ### Upgrading
426
352
 
427
353
  ```bash
428
- dsh plugin --profile desktop add dsh-retrace@0.4.131
354
+ dsh plugin --profile desktop add dsh-retrace@0.4.139
429
355
  # then restart DSH — plugins are not hot-reloaded
430
356
  ```
431
357
 
432
- **`0.4.27` and `0.4.31` were withdrawn** (briefly published, then recalled and marked
433
- deprecated on npm). Their replacements carry every fix they had.
358
+ **`0.4.27` and `0.4.31` are marked deprecated on npm.** Their replacements carry every
359
+ fix they had.
434
360
 
435
361
  **No data migration is required.** The session format is unchanged (v3), no session is
436
362
  re-written, and nothing has to be re-indexed: upgrade, restart, and the symptoms above
@@ -449,8 +375,8 @@ whole tree down, so recover first and diagnose second:
449
375
 
450
376
  ### Pinning
451
377
 
452
- Pin an exact plugin version (`dsh-retrace@0.4.131`) and let `dsh-log-contract` resolve to
453
- `>=0.3.12`. Do not rely on `^0.4` across a host upgrade: compatibility here is decided by
378
+ Pin an exact plugin version (`dsh-retrace@0.4.139`) and let `dsh-log-contract` resolve to
379
+ `>=0.3.18`. Do not rely on `^0.4` across a host upgrade: compatibility here is decided by
454
380
  the **host surface**, not by semver alone.
455
381
 
456
382
  ---
@@ -460,7 +386,7 @@ the **host surface**, not by semver alone.
460
386
  | Item | Declaration |
461
387
  |---|---|
462
388
  | **Node.js** | `>=20.0.0` (see `package.json#engines`) |
463
- | **DSH** | `>=0.1.5 <0.2.0` (see `package.json#dsh.compatibility`); desktop and web modes supported |
389
+ | **DSH** | `>=0.1.5 <0.3.0` (see `package.json#dsh.compatibility`); desktop and web modes supported |
464
390
  | **Runtime files** | All files needed at runtime are **committed** in this repository and declared in `package.json#files` (`lib/**`, `cordis.patch.yml`, `README*.md`, `HUMANS.txt`, `LICENSE`) |
465
391
  | **Build output** | Build output is committed (`lib/client.bundle.js`, `lib/dynamic-client.js`, `lib/dynamic-host.js`) and reproducible in-repo: `pnpm i && pnpm build` (`scripts/generate-dynamic.mjs`, `scripts/build-client.mjs`) |
466
392
  | **Single-file size** | Every distributed file is **below 256 KiB** (largest ≈ 249 KB) |
@@ -513,10 +439,9 @@ the **host surface**, not by semver alone.
513
439
  ops (`sessionBadge` / `setBadgeTitle` / `initBadgeTitles` / `badgeMap`) and the
514
440
  `retrace` CLI (see below).
515
441
 
516
- **What's next** — the agent business-layer plan (runtime guard, interruption
517
- governance, ecosystem-facing interfaces) is **not published yet**: it is a plan,
518
- not a shipped capability. This README describes the **development line (main)**,
519
- which may run ahead of the latest npm release.
442
+ **What's next** — see [docs/PLAN.md](./docs/PLAN.md) (next steps) and
443
+ [docs/ROADMAP.md](./docs/ROADMAP.md) (capability roadmap). This README describes the
444
+ **development line**, which may run ahead of the latest npm release.
520
445
 
521
446
  ---
522
447
 
@@ -555,7 +480,7 @@ npm pack --dry-run # verify the published file list
555
480
  > one and only swaps the transport (`host.call` vs the HTTP route) via
556
481
  > `__setMessageEditorWire`.
557
482
 
558
- PRs and issues are welcome — a `CONTRIBUTING.md` is coming soon; use the issue
483
+ PRs and issues are welcome — use the issue
559
484
  tracker linked from this package's `repository`/`bugs` metadata.
560
485
 
561
486
  ---
package/README.zh.md CHANGED
@@ -28,6 +28,10 @@
28
28
 
29
29
  ---
30
30
 
31
+ > 版本索引:[VERSIONS.md](./VERSIONS.md)
32
+
33
+ > 0.4.139 **已发布到 npm**——安装/固定版本请用当前 npm latest `0.4.135`(见 [VERSIONS.md](./VERSIONS.md));下文的 `dsh-retrace@0.4.139` 示例在该版本发布后适用。
34
+
31
35
  ## ⚡ 一分钟安装
32
36
 
33
37
  > 需要带 `dsh` CLI 的 DeepSeek Harness;装完**重启 DSH** 生效(运行中的应用不会热加载)。
@@ -82,11 +86,12 @@ dsh plugin --profile desktop add dshmarket # 只需一次
82
86
  |---|---|---|
83
87
  | 🕘 | **读档点** | 对话视图里的「读档点」Tab:每个改动(类型/时间/消息数/文件变更徽标),经 `session/projection` 推送帧实时更新(零轮询),大列表窗口化;嵌套历史按大纲逐层展开 |
84
88
  | ↩️ | **产物回退** | 仅对话 / 仅产物 / 两者,先干跑预览再执行;git 优先 + 内容寻址快照兜底;回退本身是新读档点(`restore`)。预览在会话运行中直接拒绝(不会出现「预览说可以、确认时才被拒」),预览/回档失败都会在界面上显示,不静默 |
89
+ | 🧬 | **谱系标识** | 新建会话自动分配稳定谱系标识;侧栏每个会话只显示一个标识(刷新不重复) |
85
90
  | 🧭 | **跳转对话** | 从读档点一键跳转到对应位置(自动翻页加载更早历史 + 锚点高亮);该点超出自动加载预算时,给出可诊断原因,而不是点了没反应 |
86
91
  | 🧹 | **存储有界** | 快照只保留最近 N 个读档点(默认 50);节流后台扫掠回收被截断的旧档 |
87
92
 
88
93
  > **损坏日志上的回档不静默**:宿主的严格重放是权威,但一条畸形事件(例如第三方写入的
89
- > `sourceEventSeqs` 区间编码行)就能毒化整次重放。这种情况会退到镜像重放,日志同时记录
94
+ > 畸形替换行)就能毒化整次重放。这种情况会退到镜像重放,日志同时记录
90
95
  > 「已降级」与原始错误,并在 wire 上把结果标为 `degraded`;连镜像都跑不了时返回结构化的
91
96
  > `replay-failed` 错误,而不是笼统的 `internal`。
92
97
 
@@ -130,7 +135,7 @@ dsh plugin --profile <name> add dsh-retrace
130
135
  ```json
131
136
  {
132
137
  "dependencies": {
133
- "dsh-retrace": "^0.4.131"
138
+ "dsh-retrace": "^0.4.139"
134
139
  },
135
140
  "dsh": {
136
141
  "profile": {
@@ -193,7 +198,7 @@ Client 半区会依据包内 `dsh.client` 元数据被自动打包进 Web 客户
193
198
  - DeepSeek Harness 需提供 `package.json` 里声明的 peer 包
194
199
  (`@deepseek-ai/dsh-session`、`@deepseek-ai/dsh-client-*`、`cordis`、`react` ——
195
200
  当前构建面向 `0.1.7-rc.2` 这一代内核)。
196
- - `dsh-log-contract >= 0.3.12`(作为依赖自动安装)。
201
+ - `dsh-log-contract >= 0.3.18`(作为依赖自动安装)。
197
202
  - 插件通过 `inject` 声明所需宿主能力
198
203
  (`sessions`、`agents`、`webServer`、`fs`、`subprocess`、`sandboxPolicy`、`jobs`)。
199
204
  缺某个能力只会让对应功能降级(例如没有 `subprocess` ⇒ 回档只用内置快照),
@@ -223,23 +228,6 @@ Client 半区会依据包内 `dsh.client` 元数据被自动打包进 Web 客户
223
228
  > (`will-prevent-unload` 处理,或退出前的询问钩子)。**桌面端退不掉时**,把设置里的
224
229
  > 「退出确认(关闭守卫)」关掉即退回官方形态(**不用重启**)。
225
230
 
226
- ### 会话谱系标识与显示名(**计划 / 默认关闭**)
227
-
228
- 谱系标识用于人机协作识别,**身份判定仍以 session id 为准**。通道
229
- (`sessionBadge` / `setBadgeTitle` / `initBadgeTitles` / `badgeMap`,HTTP + harness 两入口)、
230
- 解析器与写护栏**均已就位**;但**启动自动写标题那条路默认关闭**
231
- (客户端开关是 `globalThis.__DSH_RETRACE_BADGE_BOOTSTRAP = true`):
232
-
233
- - 会话标题显示为 `[谱系标识] 原标题`——**稳定标识由会话 id 确定性导出**,标题变化不影响它。
234
- - **没有 `session/title` 事件的会话如实留空**(标题只显示 `[谱系标识]`)—— **不回落项目名、不伪造名字**。
235
- - 解析器不可用时退回**原始 session id 占位**。
236
- - 侧栏会话行、运行中横幅、读档点视图的谱系标识**同源**:都取宿主下发的**同一份**映射(宿主 op `badgeMap`)。
237
-
238
- > **计划(未上线)**:agent 业务层规划(运行时守护、中断治理、生态开放接口)属**计划**,
239
- > 不是已上线能力。
240
-
241
- ---
242
-
243
231
  ## ⚙️ 设置 → 通用
244
232
 
245
233
  | 设置项 | 默认 | 说明 |
@@ -303,68 +291,25 @@ Client 半区会依据包内 `dsh.client` 元数据被自动打包进 Web 客户
303
291
 
304
292
  本节的目的:让你能分清 **宿主侧破坏性变更** 与 **插件侧缺陷**。提 issue 前请先看这节。
305
293
 
306
- ### 本插件适配过的宿主侧破坏性变更 —— *不是本插件造成的*
307
-
308
- 1. **`@deepseek-ai/dsh-session` 移除了 `Session.events` 成员**(`0.1.5-rc.1`)。
309
- 官方支持的读口是 `snapshotEvents(fromSeq, toSeqExclusive)`(冻结、按 seq 索引)、
310
- `eventAt(seq)`、`ownEvents()`、`isOwnSeq(seq)`。修复前,撤回与编辑点了没反应,并冒出
311
- `TypeError: Cannot read properties of undefined (reading 'length')`。现在插件经
312
- 兼容访问器读日志(新 API 优先、旧数组回退),两代宿主都能跑。
313
- 2. **`@deepseek-ai/dsh-session` 把 `decodeStorageRecord` 从公开导出面拿掉了**
314
- (`0.1.5-rc.1`;函数仍在内部模块里,但不再从包根导出、exports map 子路径也不可达)。
315
- 本插件自己从未 import 它,但它的依赖 `dsh-log-contract` import 了。宿主不再导出该符号时,
316
- 加载器会以
317
- `plugin tree failed to load … does not provide an export named 'decodeStorageRecord'`
318
- 中止,而且**整棵插件树一起失败——不只是本插件**,于是 App 起不来。
319
- → **依赖说明:** 需要 `dsh-log-contract >= 0.3.12`。
320
- 3. **一个客户端**服务**消失了:`conversationEvents`** —— 它原先由旧客户端运行时
321
- `@deepseek-ai/dsh-client-runtime` 提供,而该运行时已被移除。插件的客户端半若仍在
322
- `export const inject` 里声明它,就**永远不就绪**:fiber 停在 **pending**,宿主据此报
323
- `renderer boot failed (plugins: …): The client Loader did not provide an error message.`
324
- —— **一个字的错误信息都没有**,窗口起不来,唯一的进法是把插件禁用。现在该服务已从
325
- `inject` 中删除,并改在 `apply` 里**防御性解析**(`uiConversation`,取不到则回退旧名)。
326
- > 注意:在 `dsh.client.inject` 里声明一个**已不存在的包**,**不会**导致启动失败 ——
327
- > 客户端加载器对认不出的条目是**静默跳过**的。真正致命的是插件等待的那个**服务名**。
328
- 4. **客户端会话存储没有 `keys()`**(`ctx.sessions`)。用 `keys()` 枚举会话的插件会**静默地
329
- 看到 0 个会话**:不崩不报,只是安全告警永不触发。现在优先用官方 `list()`、回退 `keys()`;
330
- 刻意**不用**「猜服务字段」兜底 —— 猜出来的空集同样是静默失败。
331
-
332
- > 以上四条都是**宿主侧移除**,写在这里是有意的:如果你在**升级宿主之后**立刻遇到这些症状,
333
- > 第一个该问的是「这份插件构建是不是早于这次移除?」,而不是「插件改坏了什么?」。
334
-
335
- ### 插件侧修复(0.4.26 – 0.4.28)
336
-
337
- - **插件数据家与会话基座合并为同一来源。** 此前插件用宿主的 home 解析器
338
- (`$DSH_HOME` → `~/.dsh`)决定自己的数据目录,而它不认识 `$DSH_SESSION_BASES` 配置的额外基座。于是当 `$DSH_HOME`
339
- 未设时,**会话从一个基座读、快照与产物库写到另一个基座**。现在快照、版本库与
340
- `verify-install` 都跟随**活动会话基座**;`$DSH_HOME` 已设时行为不变。
341
- - **不再有任何用户可见文案写死 `~/.dsh`**(设置页原先提示快照存于 `~/.dsh`)。
342
- - **编辑/撤回入口从不出现。** 客户端半区从 `snapshot.chat.nodes` 读聊天节点,而本宿主没有
343
- 这条路径 —— 节点在 `useChat` 的 `snapshot.nodes` 里。所有消息级组件渲染时抛错、被错误
344
- 边界吞掉,于是按钮消失,而不读节点的设置项显示正常。
345
- - **读档点视图里的「跳转」点了毫无反应。** 它经 `store.getSnapshot()?.chat?.nodes` 解析锚点,
346
- 而该路径在此恒为 `undefined`。现在改为用视图注入的 `useChat` 快照解析,并用官方
347
- `store.loadThrough(seq)` 分页;跳不过去时给出**可诊断理由**(renderer 警告 + 宿主日志行),
348
- 不再静默失败。
349
- - **设谱系标识会冲掉用户标题。** 谱系标识入标题现在**只走服务端** `setBadgeTitle`(从会话日志读当前
350
- 标题)。手动重命名不受影响。
351
- - **宿主侧操作失败重新有日志**(code + message + stack)。此前只把 message 回传界面、不写日志,
352
- 这类问题因此很难从外部诊断。
353
- - **读档点视图现在会自我解释。** 此前只有标题加一排动作,**没有任何一句话说明「读档点」是什么**,
354
- 行内还直接显示裸节点类型。现在有常显的概念解释句、类型图例,以及每行恒有的白话「为什么」行。
355
- - **客户端隐藏判定不再逐行重扫。** `useSeqHidden` 此前每行都重扫节点表
356
- (实测 2000 行/20 marker **346ms**、3000/30 **1568ms**)。现在复用同一份 per-snapshot
357
- 隐藏计划:分别是 **8.3ms** 与 **18.3ms**,且行为判定与旧谓词逐字等价。
294
+ ### 宿主侧变更须知
295
+
296
+ 宿主升级偶尔会移除插件依赖的 API —— 这些是**宿主侧变化,不是插件缺陷**,一行一条:
297
+
298
+ - 升级后开机循环/恢复界面 → 切到干净会话并重启 DSH(插件降级而非阻断)。
299
+ - 版本/检查点面板为空 → `dsh plugin --profile <p> add dsh-retrace` 刷新 bundle。
300
+ - 标题/重命名行为变化 → 自动标题路径由宿主守卫,手动重命名不受影响。
301
+ - 依赖下限:`dsh-log-contract >= 0.3.18`。
302
+
303
+ 历史细节与原始报错见 [CHANGELOG.md](./CHANGELOG.md);兼容矩阵见 [docs/COMPAT.md](./docs/COMPAT.md)。
358
304
 
359
305
  ### 升级
360
306
 
361
307
  ```bash
362
- dsh plugin --profile desktop add dsh-retrace@0.4.131
308
+ dsh plugin --profile desktop add dsh-retrace@0.4.139
363
309
  # 然后重启 DSH —— 插件不会热重载
364
310
  ```
365
311
 
366
- **`0.4.27` 与 `0.4.31` 已撤回**(短暂发布后撤回、npm 上标记 deprecated);它们的替代版本
367
- 包含其全部修复。
312
+ **`0.4.27` 与 `0.4.31` 在 npm 上标记为 deprecated**;它们的替代版本包含其全部修复。
368
313
 
369
314
  **不需要数据迁移。** 会话格式未变(v3),不改写任何会话,也不需要重建索引:升级、重启即可。
370
315
  若宿主仍提供旧成员,兼容访问器会让那些路径继续可用 —— 本构建不丢弃老宿主。
@@ -379,7 +324,7 @@ dsh plugin --profile desktop add dsh-retrace@0.4.131
379
324
 
380
325
  ### 版本固定建议
381
326
 
382
- 请固定到确切版本(`dsh-retrace@0.4.131`),并让 `dsh-log-contract` 解析到 `>=0.3.12`。
327
+ 请固定到确切版本(`dsh-retrace@0.4.139`),并让 `dsh-log-contract` 解析到 `>=0.3.18`。
383
328
  **不要在跨宿主升级时依赖 `^0.4` 这种范围**:这里的兼容性由**宿主的面**决定,光看 semver 不够。
384
329
 
385
330
  ---
@@ -401,6 +346,8 @@ dsh plugin --profile desktop add dsh-retrace@0.4.131
401
346
 
402
347
  ## 🗺️ 路线图
403
348
 
349
+ > 详细下一步与方向:[docs/PLAN.md](./docs/PLAN.md) | 能力路线:[docs/ROADMAP.md](./docs/ROADMAP.md)
350
+
404
351
  **当前已具备(0.4.x):**
405
352
 
406
353
  - 撤回 / 重发 / 重新生成——每次回退都过**三层写前校验**与安全编辑路径(自动停 agent、临时 step 包裹 marker),**新的回退不会损坏日志、不新增 `/compact` 债**;**旧单段 marker 需要压缩前清理**(配套 `check` + `fix --remove-markers`)。
@@ -452,7 +399,7 @@ npm pack --dry-run # 校验发布文件清单
452
399
  > 发布版共用同一份 client 源码,仅通过 `__setMessageEditorWire` 切换传输层
453
400
  > (`host.call` vs HTTP 路由)。
454
401
 
455
- 欢迎提交 PR 与 issue —— `CONTRIBUTING.md` 筹备中;问题追踪入口见本包
402
+ 欢迎提交 PR 与 issue —— 问题追踪入口见本包
456
403
  `repository`/`bugs` 元数据里的链接。
457
404
 
458
405
  ---
@@ -517,15 +464,19 @@ retrace lineage <session> # 会话 parent 链谱系
517
464
  `parentSession` 接续链遍历(只读、带环保护),与 CLI `retrace lineage` 同一语义 ——
518
465
  任何客户端都能查到「这个会话是从哪个会话接着干/分叉出来的」,也是分叉拓扑的元数据源。
519
466
 
520
- ## 兼容性与运行契约(Compatibility & runtime contract)
467
+ ### 兼容性与运行契约(Compatibility & runtime contract)
521
468
 
522
469
  | 项 | 声明 |
523
470
  |---|---|
524
471
  | **Node.js** | `>=20.0.0`(见 `package.json#engines`) |
525
- | **DSH** | `>=0.1.5 <0.2.0`(见 `package.json#dsh.compatibility`;桌面与 Web 两种模式均支持) |
472
+ | **DSH** | `>=0.1.5 <0.3.0`(见 `package.json#dsh.compatibility`;桌面与 Web 两种模式均支持) |
473
+ | **运行所需文件** | 运行时所需文件**全部随仓库提交**并在 `package.json#files` 声明(`lib/**`、`cordis.patch.yml`、README 等) |
474
+ | **单文件体积** | 每个分发文件 **< 256 KiB**(最大约 249 KB) |
526
475
  | **构建产物** | 运行所需构建产物**随包提交**(`lib/client.bundle.js`、`lib/dynamic-client.js`、`lib/dynamic-host.js`);仓库内可复现:`pnpm i && pnpm build`(生成器 `scripts/generate-dynamic.mjs`、`scripts/build-client.mjs`) |
527
476
  | **运行时依赖** | `dsh-log-contract`(日志契约校验)、`zod`(参数校验);**不联网、不下载额外代码** |
528
477
  | **宿主依赖(peer)** | `@deepseek-ai/cordis` 与若干 `@deepseek-ai/dsh-*` 客户端包(由 DSH 提供,不由本插件分发) |
529
478
  | **权限 / 外部服务** | 只读写本机会话数据目录与会话日志;**不访问外部服务、不上报数据**;不改动 DSH 安装目录之外的系统路径 |
530
479
  | **失败边界** | 所有写入(撤回/编辑/恢复/回档)均在**目标文件之外先备份**、写后做帧级校验与折叠重放;失败即中止并保留原文件;不可判定时按"拒绝 + 可操作提示"处理,不静默降级 |
531
480
  | **可回退** | 每个操作都有可逆路径;本地管理脚本可一键回退到上一快照 |
481
+
482
+ - 稳定标识由会话 id 确定性导出(无随机后缀);对同一会话重复读取得到同一个标识。
package/bin/retrace.mjs CHANGED
File without changes
@@ -0,0 +1,92 @@
1
+ /**
2
+ * dsh-retrace — lib/adapter/compaction-backend.js
3
+ *
4
+ * 注册官方 compaction 后端 = **适配器 2**。
5
+ *
6
+ * 分层
7
+ * - 业务核心(fold-summary/fold-boundary/context-level)= 载体无关纯函数,零改动;
8
+ * - 适配器 1 = retrace.fold(DSH foldSurface 主动折叠,已实现);
9
+ * - 适配器 2 = 本文件:官方 BasicCompactionEngine 子类,**自动折叠**(压力/溢出自动触发),
10
+ * 摘要 = 核心确定摘要(非 LLM)——零 LLM 调用 = 零 token 成本 + 确定性;
11
+ * - 未来平台 = 新适配器实现同一 core-contract,核心不动。
12
+ *
13
+ * 官方机制(桌面捆绑 dsh-compaction-basic,源码实读):
14
+ * - BasicCompactionEngine extends CompactionEngine(cordis Service);
15
+ * - `summarize(input, agent, signal)` 是**唯一子类定制钩子**(源码注释明示);
16
+ * - 触发(thresholdRatio 0.8 自动压力 / context-overflow 恢复)、范围(
17
+ * selectCompactableRange)、保尾(retainRatio 0.16)、装配(agent/pre-step 监听)、
18
+ * 落盘(compaction/start…end + checkpoint marker)全部继承官方;
19
+ * - 我们只把「LLM 摘要」换成「核心确定摘要」:输入 input.messages(派生消息,
20
+ * 官方 buildSummarizationInput 已按 surface 序取好)→ buildSummaryFromMessages。
21
+ *
22
+ * 装配:本文件不自动注册——由 register-compaction-backend.js 装配(opt-in)。
23
+ * ⚠️ 标准桌面宿主已装官方 compaction-basic,cordis 同名注册=拒绝,
24
+ * 插件单方不可替换 → 交付口径 = 无官方后端宿主下的确定性自动折叠(见 register 模块头)。
25
+ * 依赖(@deepseek-ai/dsh-compaction-basic)仅桌面宿主存在 → 动态 import + 降级友好:
26
+ * 找不到包/宿主未装配时创建函数返回 null,调用方静默跳过(不崩插件)。
27
+ */
28
+ import { buildSummaryFromMessages } from '../fold-summary.js'
29
+
30
+ /**
31
+ * 创建确定摘要 compaction 后端(官方 BasicCompactionEngine 子类)。
32
+ * @param {object} deps
33
+ * @param {object} deps.basic - @deepseek-ai/dsh-compaction-basic 模块(动态注入,便于测试桩)。
34
+ * @param {object} deps.buildSummary - 核心摘要函数(默认 buildSummaryFromMessages,可注入测试)。
35
+ * @param {string} [deps.summaryKind] - 摘要类型标签(日志用,默认 'retrace-deterministic')。
36
+ * @returns {Function} create(ctx, config) → 后端实例;basic 缺失时 create 返回 null。
37
+ */
38
+ export function createDeterministicCompactionBackend(deps) {
39
+ const { basic, summaryKind = 'retrace-deterministic' } = deps
40
+ if (!basic?.BasicCompactionEngine) {
41
+ return () => null // 宿主无官方 compaction-basic → 不装配(降级)
42
+ }
43
+ const { BasicCompactionEngine } = basic
44
+ // 默认核心确定摘要(消息版);可注入(测试/未来平台复用同一 create)
45
+ const summarize = typeof deps.buildSummary === 'function' ? deps.buildSummary : buildSummaryFromMessages
46
+
47
+ /** 子类:唯一覆写点 = summarize(官方源码注释:sole subclass customization hook)。 */
48
+ class DeterministicCompactionBackend extends BasicCompactionEngine {
49
+ static inject = BasicCompactionEngine.inject
50
+
51
+ /**
52
+ * 用核心确定摘要替代 LLM 摘要:input.messages(派生消息,官方已按 surface 序排好)
53
+ * → buildSummaryFromMessages → 固定模板文本块。零 LLM 调用。
54
+ * @param {object} input - { system?, tools?, messages }(官方 buildSummarizationInput)。
55
+ * @param {object} agent - 官方 agent(未用,兼容签名)。
56
+ * @param {object} signal - 官方取消信号(未用——本地纯函数瞬间完成)。
57
+ * @returns {Promise<{summary: Array<{type:'text',text:string}>, llmStreamCall:boolean, provider:string, model:string, kind:string}>}
58
+ */
59
+ async summarize(input, agent, signal) {
60
+ const messages = Array.isArray(input?.messages) ? input.messages : []
61
+ const text = summarize(messages)
62
+ if (!text || !text.trim()) {
63
+ throw new Error(`retrace deterministic compaction produced empty summary (${messages.length} messages)`)
64
+ }
65
+ return {
66
+ summary: [{ type: 'text', text }],
67
+ // rawOutput 不返回(undefined)→ 官方 commitCompactionBody 的
68
+ // callProvenance = {}(llmStreamCall!==true 且 rawOutput===undefined);空数组会
69
+ // 落盘误导性 rawOutput:[] 事件字段。
70
+ llmStreamCall: false, // 零 LLM:官方据此省略 rawOutput/usage 记账
71
+ provider: 'retrace',
72
+ model: summaryKind,
73
+ kind: summaryKind,
74
+ }
75
+ }
76
+ }
77
+
78
+ /** create(ctx, config):与官方 BasicCompactionEngine 同签名(继承其 Config 校验)。 */
79
+ return (ctx, config = {}) => {
80
+ const instance = new DeterministicCompactionBackend(ctx, {
81
+ ...config,
82
+ auto: config.auto !== false, // 默认开启自动压力触发(与官方默认一致)
83
+ })
84
+ // 实例盖静态标记,register 探测用它(不依赖 constructor.name,
85
+ // 打包压缩/宿主包装后名字不可靠)。
86
+ try { Object.defineProperty(instance, RETRACE_BACKEND_TAG, { value: true, configurable: false, enumerable: false }) } catch { /* 只读宿主实例(理论不可能)忽略 */ }
87
+ return instance
88
+ }
89
+ }
90
+
91
+ /** 实例标记(register 探测 retrace 后端用;压缩安全,不依赖类名)。 */
92
+ export const RETRACE_BACKEND_TAG = Symbol.for('dsh-retrace.compaction-backend')
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * dsh-retrace — lib/adapter/contract.js
3
3
  *
4
- * 适配器层契约——业务层与平台解耦的接口定义。
4
+ * adapter layer 契约——业务层与平台解耦的接口定义。
5
5
  * **契约运行时化**:契约不再只是 JSDoc
6
6
  * 声明——跨层边界处的形状在**运行时**被断言,违反时抛出**指名道姓**的错误
7
7
  * (哪个契约 / 期望什么 / 实际什么),不再"以奇怪方式炸"或静默通过。
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * 三个角色:
13
13
  * - 业务层:message-list.js(纯函数,零依赖)——消费「通用事件」,产出消息列表/遮蔽;
14
- * - 适配器层(本文件):定义「事件读取器」和「替换写入器」两个接口 + 运行时校验;
14
+ * - adapter layer(本文件):定义「事件读取器」和「替换写入器」两个接口 + 运行时校验;
15
15
  * - 平台实现:dsh.js / dsh-writer.js(DSH 实现)、未来 self-runtime-adapter.js 等。
16
16
  *
17
17
  * 通用事件格式(业务层消费的最小形态):
@@ -38,7 +38,7 @@ import { editorError, editorId, lastModelSource } from '../host-core.js'
38
38
  // 重放时对不上"的载体)。
39
39
  import { assertContract, assertSpanShape, assertMarkerShape, assertAuditShape, runtimeSurfaceOpShape, contractViolation } from './contract.js'
40
40
  // 载体形状/文案的唯一真相(纯模块零 import;生成动态件时与 contract 一同 inline)。
41
- import { AUDIT_EVENT_TYPE, CARRIER_EVENT_TYPE, CARRIER_SOURCE_KIND, TRACE_TEXT } from '../marker-carrier.js'
41
+ import { AUDIT_EVENT_TYPE, CARRIER_EVENT_TYPE, CARRIER_SOURCE_KIND, TRACE_TEXT, AUTOFOLD_HARD_DISABLED, isAutoFoldSource } from '../marker-carrier.js'
42
42
  // Host event-view compatibility (new host: snapshotEvents/eventAt; old host: events array).
43
43
  import { sessionEvents, eventAt, nextAppendSeq } from '../host-compat.js'
44
44
 
@@ -214,6 +214,16 @@ export function createDshMarkerWriter({ validateMarker, log = () => {}, meter, d
214
214
  * @returns {Promise<object>} 第 2 段事件(调用方读 seq/surfaceOp)。
215
215
  */
216
216
  async writeMarker(session, span, meta) {
217
+ // ── 自动折叠默认关闭(最底层闸,需显式开启)─────────────────────────
218
+ // 判定收敛在 marker-carrier.isAutoFoldSource(op='fold' 且未声明用户发起);
219
+ // AUTOFOLD_HARD_DISABLED=true ⇒ 拒写并返回显式错误码,零落盘(审计段/载体段
220
+ // 都不写)。拒写留一行可核日志:走注入的宿主 logger(console.log 进不了宿主
221
+ // 日志,排障时拿不到证据)。手动 recall / edit / regenerate 与用户显式
222
+ // 折叠(userInitiated)不受影响。
223
+ if (AUTOFOLD_HARD_DISABLED && isAutoFoldSource(meta)) {
224
+ log(`retrace: HARD-BLOCK 拒写自动触发的折叠 marker(AUTOFOLD_HARD_DISABLED=true):op=${String(meta?.op ?? '')} session=${String(session?.id ?? '')} targetSeq=${String(meta?.targetSeq ?? '')} span=${String(span?.start ?? '?')}..${String(span?.end ?? '?')} — 零写入`)
225
+ throw editorError('autofold-hard-disabled', '自动触发的折叠默认关闭(AUTOFOLD_HARD_DISABLED=true):本次 marker 零落盘;手动编辑/撤回与用户显式折叠不受影响。')
226
+ }
217
227
  // 契约边界:业务层 → 适配器。span 不合规(空/倒置/非连续段)在这里立刻报错,
218
228
  // 不进入形状翻译——否则会写出 surfaceOp 与 sourceEventSeqs 不一致的载体
219
229
  // (会话面上的遮蔽范围与日志记录分叉,历史上正是这类不一致导致加载失败/编辑死锁)。
@@ -340,6 +350,70 @@ export function createDshMarkerWriter({ validateMarker, log = () => {}, meter, d
340
350
  assertPairing(session, finalAuditSeq, carrier)
341
351
  return carrier
342
352
  },
353
+
354
+ /**
355
+ * 「原文回收」副本的**单段追加**写入 —— 语义 = append 一份可读副本/恢复标记
356
+ * (host-core 的 `reclaim` op 走这里;op 段随 meta.op 写入,现役 = 'reclaim')。
357
+ *
358
+ * 为什么是单段 append 而不是两段 replace 载体(逐条):
359
+ * ① 回收的产出是「被撤回原文的可读副本」,只**新增**一条人读行;两段 replace
360
+ * 载体会把一个区间移出模型面 —— 方向相反(那是遮蔽,不是回收);
361
+ * ② **成对审计未被绕过,而是不适用**:两段路径的成对纪律(第 1 段
362
+ * `compaction/prune` = shadow-price claim,与第 2 段紧邻成对,见 writeMarker
363
+ * 与 assertPairing)原样保留;本路径一条 claim 都不写 —— 回收副本不遮蔽任何
364
+ * 节点,写 claim 会留下无人消费的孤儿审计行(真实会话里出现过的
365
+ * 形态)。单段 append 无第 1 段 ⇒ 无"半对"可言;
366
+ * ③ 自动折叠默认关闭的闸(AUTOFOLD_HARD_DISABLED + isAutoFoldSource)只判
367
+ * `op === 'fold'`:本写入的 op 是回收,不落在该闸上;那道闸的代码一行不动;
368
+ * ④ 写入前过注入的 `validateMarker`(prewrite-guard 完整契约校验,信封不带 seq
369
+ * —— 与 unhide 取消标记同规),与 marker 写入共用同一条校验链;
370
+ * ⑤ 既有行零改动:append-only,正本(被遮蔽原文 + 两段 marker)一个字节不动。
371
+ *
372
+ * 形状(与 unhide 取消标记同一承载形态:单段 `user/message` + `surfaceOp:'append'`):
373
+ * data = { role, id, op, restores, sourceSeqs, content, source } —— 四成员官方
374
+ * 词表 + 业务成员(内核消息形状校验只查 id/role/source/content,加成员合法)。
375
+ * `source.kind = 'model'`:轮边界谓词只认 kind==='user',写 'user' 会被当成
376
+ * 真实用户输入、切分交换轮(marker-carrier 文件头「轮边界」)。
377
+ */
378
+ async writeRestoreCopy(session, meta) {
379
+ const op = String(meta?.op ?? '')
380
+ // fold 由两段路径承载;本写入只承载回收类单段副本(fail-closed:op 缺失/为 fold 一律拒)。
381
+ if (op === '' || op === 'fold') {
382
+ throw editorError('bad-request', `writeRestoreCopy 只写回收类单段副本,op 必为非 fold 的业务 op(收到 ${JSON.stringify(meta?.op ?? null)})`)
383
+ }
384
+ const content = Array.isArray(meta?.content)
385
+ ? meta.content.filter((b) => b && b.type === 'text' && typeof b.text === 'string' && b.text.length > 0)
386
+ : []
387
+ if (content.length === 0) {
388
+ throw editorError('bad-request', 'writeRestoreCopy 需要非空 content(回收副本即可读原文;空 content 会投影成空消息)')
389
+ }
390
+ const model = lastModelSource(session)
391
+ if (!model) {
392
+ throw editorError(
393
+ 'no-model-header',
394
+ 'This session has no model header yet; send at least one message before reclaiming a recall.',
395
+ )
396
+ }
397
+ const data = {
398
+ role: 'user',
399
+ id: editorId(op),
400
+ op,
401
+ ...(Number.isSafeInteger(meta?.restores) && meta.restores >= 0 ? { restores: meta.restores } : {}),
402
+ ...(Array.isArray(meta?.sourceSeqs)
403
+ ? { sourceSeqs: meta.sourceSeqs.filter((s) => Number.isSafeInteger(s)) }
404
+ : {}),
405
+ content: carrierContentOf(meta, deriveContentText),
406
+ source: { kind: CARRIER_SOURCE_KIND, provider: model.provider, model: model.model },
407
+ }
408
+ const envelope = { type: CARRIER_EVENT_TYPE, data, surfaceOp: 'append' }
409
+ if (typeof validateMarker === 'function') {
410
+ await validateMarker(session, envelope)
411
+ }
412
+ if (!guardDurableAppend(session, log, 'restore-copy')) {
413
+ throw contractViolation('dshAdapter.writeRestoreCopy.turn-boundary', '会话运行中,拒绝持久 append(restore-copy):轮边界外', session?.id)
414
+ }
415
+ return session.append(CARRIER_EVENT_TYPE, data, { surfaceOp: 'append' })
416
+ },
343
417
  }
344
418
  }
345
419